This is Part 4 of 7 in a tutorial on using code to integrate Excel and Access.
In the sample file, Table Download is blank and contains two buttons. By pressing Download Table you will populate the sheet with everything in tblPopulation.
Note:
The constant is shown below.
Const TARGET_DB = "DB_test1.mdb"
The code does the following:
Sub TransferTableFromAccess()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim fld As ADODB.Field
Dim MyConn
Dim i As Long
Dim ShDest As Worksheet
Set ShDest = Sheets("Table download")
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
With cnn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Open MyConn
End With
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:="tblPopulation", _
ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, _
LockType:=adLockOptimistic, _
Options:=adCmdTable
'clear existing data on the sheet
ShDest.Activate
Range("A1").CurrentRegion.ClearContents
'create field headers
i = 0
With Range("A1")
For Each fld In rst.Fields
.Offset(0, i).Value = fld.Name
i = i + 1
Next fld
End With
'transfer data to Excel
Range("A2").CopyFromRecordset rst
' Close the connection and clean up references
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
End Sub