VBA to write data to Access file

Here’s an example of VBA code that writes data to an Access database file (.mdb or .accdb) using ADO (ActiveX Data Objects):

Sub WriteDataToAccess()
    Dim conn As Object ' ADODB.Connection
    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 data to be written to the database
    Dim fieldValue As String
    fieldValue = "Hello, World!" ' Replace with your data
    
    ' 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 the SQL INSERT statement
    strSQL = "INSERT INTO TableName (FieldName) VALUES ('" & fieldValue & "')" ' Replace TableName and FieldName with the actual table and field names
    
    ' Execute the SQL statement
    conn.Execute strSQL
    
    ' Close the connection
    conn.Close
    
    ' Clean up the object
    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" and "FieldName" with the actual table and field names where you want to write the data.

The fieldValue variable contains the data you want to write to the Access database. You can customize it according to your requirements. The example provided writes the string “Hello, World!” to the specified field.

When you run this code, it will establish a connection to the Access database using ADO, create an SQL INSERT statement with the data, execute the statement to write the data to the database, close the connection, and clean up the objects.

Note: Make sure that the specified Access database file exists in the specified path and that the table and field names are accurate.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech