VBA code that interacts with a Microsoft Access database


 Sub AccessDatabase()


    ' Declare variables

    Dim db As DAO.Database

    Dim rs As DAO.Recordset

    Dim sql As String

    

    ' Set the SQL statement to retrieve data from the database

    sql = "SELECT * FROM Customers"

    

    ' Open a connection to the database

    Set db = OpenDatabase("C:\path\to\your\database.accdb")

    

    ' Execute the SQL statement and retrieve the data into a recordset

    Set rs = db.OpenRecordset(sql)

    

    ' Loop through the recordset and print the values to the Immediate window

    Do While Not rs.EOF

        Debug.Print rs!CustomerID & " " & rs!CompanyName

        rs.MoveNext

    Loop

    

    ' Close the recordset and the database

    rs.Close

    db.Close

    

End Sub


This code opens a connection to an Access database, executes a SQL statement to retrieve data from the "Customers" table, loops through the resulting recordset, and prints the values to the Immediate window. You can modify the SQL statement to retrieve different data, and use other methods and properties of the DAO.Database and DAO.Recordset objects to interact with the database.


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.