Curious Minds

Clear answers to science and history questions

Access VBA Add Record to Table: DAO and SQL Methods

· 6 min read · Science

To add a record to a table in Access VBA, use either the DAO Recordset method (open a recordset, call AddNew, assign field values, then Update) or execute an SQL INSERT statement via CurrentDb.Execute. Both approaches work in any version of Access that supports VBA, and the choice depends on whether you need to manipulate the record before saving or simply insert one or more rows.

Background: Why VBA for Data Entry?

Microsoft Access is a desktop database that combines a Jet/ACE database engine with a forms-and-reports front end. VBA (Visual Basic for Applications) is the programming language built into Access for automating tasks that go beyond what macros or bound forms can do. Adding records programmatically is a common need: importing data from external files, duplicating a record with modifications, creating audit log entries, or populating a table from a custom unbound form.

Access exposes two main data-access libraries: DAO (Data Access Objects) and ADO (ActiveX Data Objects). DAO is the native library for the Jet/ACE engine and is generally preferred for working with local Access tables. ADO is more generic and can connect to other databases, but for simple inserts into an Access table, DAO or an SQL statement is simpler and faster.

Method 1: DAO Recordset with AddNew

The DAO Recordset approach gives you full control over the record before it is written. You open a recordset on the target table, call AddNew to create a blank record buffer, assign values to each field, then call Update to commit the record. If you omit Update, the record is discarded.

  1. Declare variables for the recordset and database objects.
  2. Set the database object to CurrentDb.
  3. Open a recordset with dbOpenDynaset (or dbOpenTable for a local table) on the target table.
  4. Call rs.AddNew.
  5. Assign values to fields: rs!FieldName = value.
  6. Call rs.Update to save the record.
  7. Close the recordset and release object variables.

Example:

Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Customers", dbOpenDynaset)
With rs
    .AddNew
    !FirstName = "Jane"
    !LastName = "Doe"
    !JoinDate = Date
    .Update
    .Close
End With
Set rs = Nothing
Set db = Nothing

This method automatically handles data types and required fields (though missing required fields will cause an error on Update). It also works well when you need to read the newly generated AutoNumber value: after Update, the recordset's !ID field (or the bookmark) reflects the new value.

Method 2: SQL INSERT Statement

An SQL INSERT statement is a single line of code that adds one or more records directly. You execute it with CurrentDb.Execute (or DoCmd.RunSQL). This method is concise and efficient for simple inserts, especially when you are inserting many records in a loop or when the values come from another table (INSERT INTO ... SELECT).

Example:

Dim strSQL As String
strSQL = "INSERT INTO Customers (FirstName, LastName, JoinDate) " & _
         "VALUES ('Jane', 'Doe', #" & Format(Date, "yyyy-mm-dd") & "#)"
CurrentDb.Execute strSQL, dbFailOnError

Note the use of dbFailOnError so that any error (such as a duplicate key or missing required field) raises a trappable error rather than failing silently. Date literals in Access SQL are delimited with # signs, and string literals with single quotes; you must escape embedded single quotes by doubling them (e.g., O''Brien).

Choosing Between DAO and SQL

  • Use DAO AddNew when you need to set many fields conditionally, when you want to retrieve the AutoNumber immediately, or when you are working with a bound form's recordset.
  • Use SQL INSERT when inserting a single record with fixed values, when inserting multiple records at once, or when the source data comes from another table or query.
  • Performance: For large numbers of inserts, SQL executed in a transaction is usually faster than repeated AddNew/Update because it avoids the overhead of opening a recordset. However, for a handful of records the difference is negligible.

Common Problems and How to Avoid Them

  • Missing required fields: If a field has Required = Yes and no default value, both methods will fail. Ensure all required fields are supplied.
  • Data type mismatches: Assigning text to a numeric field or a date in the wrong format causes errors. Use the correct data type and format date literals as #yyyy-mm-dd# to avoid locale issues.
  • Duplicate primary key: If the table has a primary key and you try to insert a duplicate value, you get an error. Use AutoNumber for surrogate keys or check for existing values first.
  • Unescaped quotes in SQL: A single quote inside a string literal breaks the SQL. Replace ' with '' or use parameterized queries (not natively supported in Access SQL, but you can use DAO parameters).
  • Forgetting Update: With DAO, if you omit rs.Update, the record is not saved and no error occurs.

Safety and Best Practices

Always wrap multiple inserts in a transaction to ensure data integrity. With DAO, use db.BeginTrans and db.CommitTrans (or Rollback on error). With SQL, you can execute BEGIN TRANSACTION and COMMIT statements, but DAO transactions are simpler. Also, validate input before inserting to avoid errors and to maintain data quality. Avoid using DoCmd.RunSQL for critical operations because it can display confirmation messages; use CurrentDb.Execute with dbFailOnError instead.

Frequently Asked Questions

Can I add a record to a linked table using VBA?

Yes. Both DAO and SQL methods work with linked tables (e.g., linked SQL Server or Access tables) as long as the linked table has a unique index. However, performance may be slower over a network, and some server-specific features (like triggers) may behave differently.

How do I get the AutoNumber value after inserting a record?

With DAO, after rs.Update, the AutoNumber field in the recordset contains the new value. With SQL, you can use SELECT @@IDENTITY immediately after the insert (within the same connection) to retrieve the last generated AutoNumber.

Why does my INSERT statement fail with a syntax error?

Common causes include missing quotes around text values, using double quotes instead of single quotes for string literals, unescaped apostrophes in text, or using reserved words as field names (enclose them in square brackets). Check the SQL string by printing it to the Immediate Window before executing.

Can I insert multiple records in one statement?

Access SQL supports inserting multiple rows with a single INSERT INTO ... VALUES statement only in newer versions (Access 2010 and later) using the syntax INSERT INTO table (field1, field2) VALUES (1, 'a'), (2, 'b'). For older versions, use a loop or INSERT INTO ... SELECT from a temporary table.

What is the difference between AddNew and INSERT INTO?

AddNew is a DAO recordset method that creates a new record in memory and requires an explicit Update to save it. INSERT INTO is an SQL statement that directly adds the record to the table in one step. AddNew gives more control for complex logic; INSERT INTO is more concise for simple inserts.

Do I need to enable DAO references?

In modern Access versions, the DAO library is referenced by default. If you get a "User-defined type not defined" error for DAO objects, open the VBA editor, go to Tools > References, and ensure "Microsoft Office X.0 Access database engine Object Library" is checked.

In this article
  1. Background: Why VBA for Data Entry?
  2. Method 1: DAO Recordset with AddNew
  3. Method 2: SQL INSERT Statement
  4. Choosing Between DAO and SQL
  5. Common Problems and How to Avoid Them
  6. Safety and Best Practices
  7. Frequently Asked Questions