Here’s an example of VBA code that reads data from an Access database file (.mdb or .accdb) using SQL queries:
Sub ReadDataFromAccess() Dim db As Object ' DAO.Database Dim rs As Object ' DAO.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 DAO Database object Set db = CreateObject("DAO.DBEngine.120").OpenDatabase(dbPath) ' Create a DAO Recordset object and execute the SQL query Set rs = db.OpenRecordset(strSQL) ' 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("FieldName") ' Replace FieldName with the actual field name in the table MsgBox fieldValue rs.MoveNext Loop End If ' Close the recordset and the database rs.Close db.Close ' Clean up the objects Set rs = Nothing Set db = 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, execute the SQL query, loop through the recordset, read the data from the specified field, and display it in a message box.