Hi - I am creating a custom ribbon in Excel to perform a variety of analysis on a dataset that is refreshed everyday. The first button I have included on the ribbon is one that I would like to import data into an Excel worksheet from an Access table. I have the following module, however, I am getting an error on line 25, ".Open". Does anyone have any idea why I am getting this error or if there is a better way to connect to a database to pull in data from a table? Thanks!
Code:
Sub Macro1(control As IRibbonControl)
'Declare variables.
Dim dbConnection As ADODB.Connection
Dim dbRecordset As ADODB.Recordset
Dim dbFileName As String
Dim strSQL As String
Dim DestinationSheet As Worksheet
'Set the assignments to the Object variables.
Set dbConnection = New ADODB.Connection
Set dbRecordset = New ADODB.Recordset
Set DestinationSheet = Worksheets("Sheet1")
'Define the Access database path and name.
dbFileName = "C:\Users\david\Documents\Database2.accdb"
'Use SQL's SELECT and FROM statements for importing Table1.
strSQL = "SELECT [Today's Date], [Request Number], [Packet #], [Inquire Type], [Description/Issue], [Comments], [State] .* FROM tblmaster;"
'Clear the destination worksheet.
DestinationSheet.Cells.Clear
With dbConnection
'Open the connection.
.Open
'The purpose of this line is to disconnect the recordset.
.CursorLocation = adUseClient
End With
With dbRecordset
'Create the recordset.
.Open strSQL, dbConnection
'Disconnect the recordset.
Set .ActiveConnection = Nothing
End With
DestinationSheet.Range("A2").CopyFromRecordset dbRecordset
DestinationSheet.Range("A1:G1").Value = _
Array("Today's Date", "Request Number", "Packet #", "Inquire Type", "Description/Issue", "Comments", "State")
'Close the recordset.
dbRecordset.Close
'Close the connection.
dbConnection.Close
'Release Object variable memory.
Set dbRecordset = Nothing
Set dbConnection = Nothing
Set DestinationSheet = Nothing
End Sub