Here’s an example of VBA code that reads data from an Access database file (.mdb or .accdb) using ADO (ActiveX Data Objects):
Sub ReadDataFromAccess() Dim conn As Object ' ADODB.Connection Dim rs As Object ' ADODB.Recordset Dim strSQL As String ' Specify the path and filename of the Access database file Dim dbPath As String dbPath = "C:\Path\to\your\Database.accdb" ' Specify the SQL query to retrieve data from the Access database strSQL = "SELECT * FROM TableName" ' Replace TableName with the actual table name or query ' Create a Connection object Set conn = CreateObject("ADODB.Connection") ' Open the Connection to the Access database conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath ' Create a Recordset object and execute the SQL query Set rs = CreateObject("ADODB.Recordset") rs.Open strSQL, conn ' Loop through the recordset and read the data If Not rs.EOF Then rs.MoveFirst Do Until rs.EOF ' Read data from the recordset and do something with it Dim fieldValue As Variant fieldValue = rs.Fields("FieldName").Value ' Replace FieldName with the actual field name in the table MsgBox fieldValue rs.MoveNext Loop End If ' Close the recordset and the connection rs.Close conn.Close ' Clean up the objects Set rs = Nothing Set conn = Nothing End Sub
In this code, you need to modify the dbPath
variable to the actual path and filename of your Access database file. Also, replace "TableName"
with the actual name of the table or query you want to retrieve data from. Inside the loop, you can access specific field values by replacing "FieldName"
with the actual field name in the table.
When you run this code, it will connect to the Access database using ADO, execute the SQL query, loop through the recordset, read the data from the specified field, and display it in a message box.