Can anybody post a snippet on how to create a reference to Microsoft DAO 3.6 object library from Excel 2007?
I gather I need to use the CreateObject method but I can't find anything online concerning the right parameters to reference DAO 3.6 specifically.
I need to late bind as I won't be able to manually set references on each PC using the file.
Many thanks
Thes best place to learn about DAO is Microsoft's Developer Network. There is a lot of documentation on the subject.
VBA supports three data access technologies. DAO, ADO and RDO. Of these Microsoft recommend you use ADO, the newer of the three.
I've been trying to write a late bound Excel DAO example, but I've run into a little trouble. I've only been able to get an early bound approach working.
Sub ExampleEarly()
Dim DB As DAO.database
Dim RS As DAO.Recordset
' Connect to Excel spreadsheet and read from tab called VA.
Set DB = OpenDatabase("C:\Example\ExcelFile.xls", False, True, "Excel 8.0;HDR=Yes")
Set RS = DB.OpenRecordset("SELECT * FROM [VA$]")
'Close the recordset
RS.Close
DB.Close
Set RS = Nothing
Set DB = Nothing
End Sub
ADO can be late bound like so:
Dim cn As Object
Dim rs AS Object
Set cn = CreateObject("ADODB.Connection")
Set rs= CreateObject("ADODB.Recordset")
For DAO late binding. Not fully tested compatibility if you use ADO in your code, but it works so far in my projects.
Dim db As Object 'late binding without reference, seems to work, but might cause trouble, not tested
Dim tbl As Object
Dim dbe As Object
Set dbe = CreateObject("DAO.DBEngine.120") 'depends on win version!
Set db = dbe.OpenDatabase(file)
Set tbl = db.TableDefs("CAPEX")
Related
I'm trying to create an Excel user form that will add newrecords to a Sharepoint List. The problem is that this form needs to be available to all users in my organization, without their being specifically permissioned to the List.
The basic URL for the Sharepoint List looks something like this:
https://myorg.sharepoint.com/personal/myname/;LIST=SubmissionsTest;
However, this link only works for me. If I try to Share the List with people in my company, Sharepoint provides me with a link that looks like this:
https://myorg.sharepoint.com/:l:/g/personal/myname/arandom50charactertextstring
Test users have confirmed they can access the List via the second link, but not the first.
To push records into the List from Excel, I've created the following VBA code:
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim mySQL As String
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
mySQL = "SELECT * FROM SubmissionsTest;"
With cnt
.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;" _
& "DATABASE=https://myorg.sharepoint.com/personal/myname/;LIST=SubmissionsTest;"
.Open
End With
rst.Open mySQL, cnt, adOpenDynamic, adLockOptimistic
rst.AddNew
rst.Fields("Title") = Int(Now() * 100000)
rst.Fields("testEntry") = "This is a test submission"
rst.Fields("testSubmitter") = Environ("UserName")
rst.Update
If CBool(rst.State And adStateOpen) = True Then rst.Close
If CBool(cnt.State And adStateOpen) = True Then cnt.Close
MsgBox "Your submission has been received."
This code works fine when I run it. As expected, it does not run for my test users. However, when I try substituting that second, Sharepoint-provided link into the Connection String, the code no longer works either for me or my test users. Instead, we receive errors telling us the SubmissionsTest object cannot be found.
I have yet to be able to figure out how I can tweak this code so that the Shareable link is recognized. Does anyone have any ideas on how this can be accomplished?
Thanks in advance for any suggestions.
OK, I found the solution after studying this posting on the Microsoft forums: https://social.technet.microsoft.com/Forums/en-US/2a1b718a-e9a5-4a1d-96a9-97804ebef769/vba-to-insert-record-to-an-existing-sharepoint-online-list?forum=sharepointgeneral
As indicated in the code above, the Connection String I was trying to use was:
DATABASE=https://myorg.sharepoint.com/personal/myname/;LIST=SubmissionsTest;
Even after permissioning the Sharepoint List for anyone in the firm, Excel reported that it was unable to find the table "SubmissionsTest". On the recommendation of the post above, I looked up the GUID values for the List. That returned a string that looked something like this:
<LIST><VIEWGUID>alongstringofalphanumericcharacters</VIEWGUID>
<LISTNAME>anotherstringofcharacters</LISTNAME>
<LISTWEB>https://myorg.sharepoint.com/personal/myname/</LISTWEB>
<LISTSUBWEB></LISTSUBWEB><ROOTFOLDER></ROOTFOLDER></LIST>
Once I changed the Connection String to this:
DATABASE=https://myorg.sharepoint.com/personal/myname/;LIST={anotherstringofcharacters};
the code now works for everyone. My conclusion is that, on SharePoint O365, table names cannot necessarily be trusted. Sometimes, the GUID values will need to be referenced directly.
In our company .xlsm, I'm using "standard" macro to send e-mails via Outlook:
Dim olApp As Object, olMail As Object
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If olApp Is Nothing Then
Set olApp = CreateObject("Outlook.Application")
End If
On Error GoTo 0
Set olMail = olApp.CreateItem(0)
With olMail
'properties, methods, events
End With
The thing is, it works on all company computers except for one. On this one:
If Outlook client is closed when running macro, everything works fine;
If Outlook client is opened when running macro, it returns Error '91' (Object variable not set) on Set olMail = olApp.CreateItem(0).
What could be the cause?
Your Excel Application must be run under the same security context with Outlook running to be able to get the running instance.
If Outlook client is opened when running macro, it returns Error '91' (Object variable not set) on Set olMail = olApp.CreateItem(0).
If you run Excel with admin privileges you need to run Outlook as well with admin privileges to be able to connect them together.
Also you may try to use the early-binding technology instead of late-binding one. For that you need to add an Outlook COM reference in the Excel COM References dialog (see the VBA editor). Read more about that in the Using early binding and late binding in Automation article.
I'm working with VBA and GuiXT separated and now I'm trying to use the SAP GUI VBA integration instead, but i think it's not working because I'm missing a permission.
I tried the code I've found in this thread:
Sub test()
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children.ElementAt(0)
SAPCon.FindById("wnd[0]").Maximize
End Sub
It runs and SAP informs me that a script tries to connect to SAP, but the line Set session = SAPCon.Children.ElementAt(0) gives me error 614: "The enumerator of the collection cannot find en element with the specified index".
So I googled and found out, that I'm missing the option "Script recording and playback" in SAP, it's greyed out. And i googled further and I found out, that I'm missing the permission to record or playback a script.
Because of that I'd like to know: if I don't have the permission in SAP to record or playback a script, then that's the reason for my not working VBA code, right?
I am trying to connect to my SQL Server in Excel VIA VBA.
I am getting stuck with the Connection string, it doesn't want to open. I keep on getting the error - Provider can not be found. It may not be properly installed.
Here is my code to connect:
Option Explicit
Const SQLConStr As String = "Provider=SQLNCLI10;Server=XXX\XXX;Database=XXX;Trusted_Connection=yes;"
Sub ConnectToDB()
Dim PolicyDetails As ADODB.Connection
Set PolicyDetails = New ADODB.Connection
PolicyDetails.ConnectionString = SQLConStr
PolicyDetails.Open
PolicyDetails.Close
Set PolicyDetails = Nothing
End Sub
I have read a few of the previous questions regarding 32-bit/ 64- bit , but everything on my computer is run on 64-bit.
Does anyone else know why is doesn't want to connect to my Database
Try using "SQLOLEDB" or "SQLNCLI11" in your SQLConStr String instead of "SQLNCLI10"
How do I get the results of a query from Access into Excel if it has a UDF?
I receive the following error: "Run-time error '3085': Undefined function 'XXXX' in expression". The error occurs when opening an (access query) recordset from Excel VBA. The query being opened has a user defined function (UDF) which is triggering the error.
The code is in Excel Office 365. The query is in Access Office 365.
I have successfully utilized the query being called (and others with the UDFs) for about twelve months, and "suddenly" it is not working any more. I have googled and tested many options with no success.
Most threads say it can't be done, or to not use a udf but try a built-in that works. I am challenging those responses because it has worked previously. The main udf I am using is one called "iMax" which is written about in other posts. It functions like max() in Excel. (No max(x,y) function in Access)
I have also seen threads that suggest executing this in two steps: 1 - change the query to a make table query. 2 - pull the table results into Excel. While I could maybe get away with this (after much rework), it would result in me making many temporary tables with thousands and thousands of rows and doesn't seem very slick.
I have compiled vba and compacted the db with no impact to my problem.
As a long shot I created a dummy database with a simple udf public function that returned the number 1, a simple query that returns three records and a field for the function results. This gets the same error when pulling into Excel.
Sub RunQuery()
Dim MyDatabase As dao.Database
Dim qdf As dao.QueryDef
Dim rs As dao.Recordset
Dim qryname As object
Dim SheetName As String
Set MyDatabase = DBEngine.OpenDatabase _
("SomePath\SomeFilename.accdb")
For Each qryname In Range("SomeRange")
Set rs = MyDatabase.OpenRecordset(qryname) '<<<ERROR IS HERE
SheetName = "SomeSheetName"
With Sheets(SheetName)
.ListObjects(SomeTableName).DataBodyRange.Rows.ClearContents
.Range("A2").CopyFromRecordset rs
End With
Set rs = Nothing
Set qdf = Nothing
Next qryname
End Sub
For all queries in the For loop that do not have a udf, the results are pulled and dumped into a series of tables in Excel. Any query with a udf errors at the "Set rs = Mydatabase.OpenRecordset(qryname)
If you run the query within an Access application session, as Gustav suggested, the expression service can handle the UDF in your query.
Here is a quick tested Excel VBA snippet which pulls data from a query which includes a UDF:
Const cstrDbFile As String = "C:\share\Access\Database2.accdb"
Dim objAccess As Object
Dim rs As Object
Dim ws As Worksheet
Dim strSelect As String
Set objAccess = CreateObject("Access.Application")
objAccess.Visible = True ' useful during testing '
objAccess.OpenCurrentDatabase "C:\share\Access\Database2.accdb"
strSelect = "SELECT ID, DummyFunction('a', '', 'c') FROM Dual;"
Set rs = objAccess.CurrentDb.OpenRecordset(strSelect)
If Not rs.EOF Then
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("A1").CopyFromRecordset rs
End If
rs.Close
objAccess.Quit
Most threads say it can't be done,
and they are right.
Your only option is to use automation to open an instance of Access and, within this, run the query.
Well, as noted, most are saying this should not work.
However, if you are 100% sure it was and did work at one time?
You need to set the "sandbox" mode of the JET (now ACE) database engine.
The expression service normally does not allow evaluation of VBA functions as a security setting to prevent SQL injection, or code running outside of Access to allow SQL to run + call VBA functions. At one time, this feature did default to "on", but now the default is set to access only.
You have to set the folder where Access application as trusted. This should allow the VBA functions to now work. so, make sure you set the folder as trusted.
If the location (folder) where your access application is NOT trusted, then Access will use sandbox mode, and VBA in the SQL will not run.
If the location is trusted, THEN access uses the registry setting on your computer.
My bets are that the location is not trusted - so you always get sandbox mode for SQL in Access.
If you are 100% sure that the folder location is set as trusted in Access, and you still receive the errors, then you have to change the registry setting for Access "sandbox" mode.
The setting in the registry is outlined here:
https://support.office.com/en-us/article/Turn-sandbox-mode-on-or-off-to-disable-macros-8CC7BAD8-38C2-4A7A-A604-43E9A7BBC4FB
The registry settings are:
for x32 bit access:
Software\Microsoft\Office\ClickToRun\Registry\Machine\Software\
Wow6432Node\Microsoft\Office\16.0\Access Connectivity Engine\Engines
The above is for Office 2016
14 = 2010
15 = 2013
16 = 2016
The key value for sandbox mode is:
0 to 3
0 Sandbox mode is disabled at all times.
1 Sandbox mode is used for Access, but not for non-Access programs.
2 Sandbox mode is used for non-Access programs, but not for Access.
3 Sandbox mode is used at all times. This is the default value, set when you install Access
So, from above, you want a setting of 0.