This is how I use VBA in Excel to connect to Access database:
'declare public constant in a general module
Public Const gconConnection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='\\server name\path\databasename.accdb'"
______________
Private Sub btnStart_Click()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open gconConnection
'get project records matching state project number
rs.Open "SELECT DISTINCT ProjectName FROM GeoDataAll WHERE StateNum='" & gstrStateNum & "';", cn, adOpenStatic, adLockReadOnly
...
End Sub
______________
But I just open recordsets and then have more code that writes data to cells. You appear to be doing something else. So I used macro recorder to try and produce code like yours. This is what generated:
Code:
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
"OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;Password="""";User ID=Admin;Data Source=R:\Lab\Database\Data\LabData.accdb;Mode=ReadWrite;Extend" _
, _
"ed Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=6;" _
, _
"Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Databas" _
, _
"e Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=Fal" _
, _
"se;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLEDB:Bypass User" _
, "Info Validation=False"), Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdTable
.CommandText = Array("Projects")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.SourceDataFile = "R:\Lab\Database\Data\LabData.accdb"
.ListObject.DisplayName = "Table_LabData.accdb"
.Refresh BackgroundQuery:=False
End With
Some of the line breaks look odd but the data imported. No idea why it broke on the words Extended, Database, False and threw commas in between - weird. I suppose just need to edit those lines.