Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Access VBA SQL INSERT: Step-by-Step Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To insert a record into an Access table from VBA, build an INSERT INTO statement string and run it with CurrentDb.Execute (or DoCmd.RunSQL). Use CurrentDb.Execute "INSERT INTO TableName (Field1, Field2) VALUES ('Text', 123)" for a quick action query, or a parameterized query with QueryDef when values come from user input. This guide shows both approaches, how to handle quotes and dates, and how to avoid the errors that make Access VBA SQL inserts fail.

What You'll Need

  • Microsoft Access desktop database (the .accdb or .mdb file) open on your computer.
  • A table with defined fields and appropriate data types. Note the exact field names; spaces or special characters require square brackets.
  • Access set to allow VBA macros. If the database shows a security warning, enable content for the current session.
  • Basic familiarity with the VBA editor: press Alt+F11 to open it, and use the Immediate Window (Ctrl+G) for quick tests.

Step-by-Step

  1. Open the VBA editor. Press Alt+F11. In the Project Explorer, right-click your database project and choose Insert > Module. A new blank module opens. (Menu labels can differ slightly by Access version and region.)
  2. Write a simple INSERT statement. In the module, create a Sub procedure. For a table named Customers with fields FirstName (Text), LastName (Text), and Age (Number), type:
    Sub InsertOneRecord()
        Dim sql As String
        sql = "INSERT INTO Customers (FirstName, LastName, Age) " & _
              "VALUES ('John', 'Smith', 30)"
        CurrentDb.Execute sql, dbFailOnError
    End Sub
    The dbFailOnError constant makes Access raise a trappable error if the insert fails, instead of silently doing nothing. You can also use DoCmd.RunSQL sql, but it shows a confirmation prompt unless you set DoCmd.SetWarnings False first; remember to turn warnings back on.
  3. Handle text values with apostrophes. If a value contains a single quote (for example O'Brien), the SQL breaks. Replace each apostrophe with two apostrophes before building the string:
    Dim name As String
    name = "O'Brien"
    name = Replace(name, "'", "''")
    sql = "INSERT INTO Customers (FirstName) VALUES ('" & name & "')"
    Do this for every text value that comes from a form or user input.
  4. Format dates and numbers correctly. Access SQL expects date literals in #mm/dd/yyyy# format (or a format that matches your regional settings; US format is safest). Numbers need no quotes. For example:
    sql = "INSERT INTO Orders (OrderDate, Amount) VALUES (#12/31/2025#, 199.95)"
    If you use a date variable, format it explicitly: Format(myDate, "\#mm\/dd\/yyyy\#").
  5. Use a parameterized query for user input. Building SQL by concatenating form fields is risky. Instead, create a saved query or use a QueryDef with parameters:
    Dim qdf As DAO.QueryDef
    Set qdf = CurrentDb.CreateQueryDef("", "PARAMETERS pFirstName Text, pAge Long; " & _
        "INSERT INTO Customers (FirstName, Age) VALUES (pFirstName, pAge);")
    qdf!pFirstName = Me.txtFirstName
    qdf!pAge = Me.txtAge
    qdf.Execute dbFailOnError
    qdf.Close
    Set qdf = Nothing
    This avoids quote-escaping and protects against SQL injection if the database is shared.
  6. Run the code. Place the cursor inside the Sub and press F5, or call the Sub from a button's Click event. Check the table to confirm the record was added.
  7. Insert multiple records. Use a loop with a recordset or execute the INSERT statement repeatedly. For a few rows, a single multi-row INSERT is not supported in Access SQL; loop instead. For many rows, open a recordset with CurrentDb.OpenRecordset("Customers", dbOpenDynaset), use .AddNew, set fields, and .Update.
  8. Insert from another table. Use INSERT INTO Target (Field1, Field2) SELECT FieldA, FieldB FROM Source WHERE .... This is a single SQL statement and works well for copying filtered data.

Common Mistakes

  • Forgetting to escape apostrophes in text values, causing a syntax error.
  • Using the wrong date format or omitting the # delimiters around dates.
  • Mismatching field names or using reserved words (such as Date or Value) without square brackets.
  • Leaving out dbFailOnError, so failures go unnoticed.
  • Concatenating raw form input into SQL, which risks injection and errors.
  • Using DoCmd.RunSQL without managing warnings, so users see prompts or warnings stay off later.

Tips

  • Test your SQL in the Access query designer first: create a query, switch to SQL view, paste the statement, and run it. Once it works, copy it into VBA.
  • Use Debug.Print sql before executing to see the exact string in the Immediate Window.
  • Prefer parameterized queries for any value that comes from a form, especially text fields.
  • If you need the new record's ID, use CurrentDb.Execute followed by SELECT @@IDENTITY in the same session, or use a recordset with .AddNew and read the autonumber field after .Update.
  • Keep a backup of the database before running bulk inserts or testing new code.

Troubleshooting

If the insert fails, check the error message. A "Syntax error in INSERT INTO statement" usually means a missing comma, an unescaped apostrophe, or a misspelled field name. "Data type mismatch" points to a date or number formatted as text, or text sent to a numeric field. "Field cannot be updated" often means you are trying to write to a calculated or autonumber field. If nothing happens at all, confirm the code actually ran (add a MsgBox) and that the table is not read-only or linked without permissions. For linked tables, ensure the back-end database is accessible and the connection is valid. If you see a security warning, enable macros for the session. When using DoCmd.RunSQL, set DoCmd.SetWarnings False before and True after to suppress prompts, but never leave warnings off permanently.

Frequently Asked Questions

Can I use INSERT INTO with multiple rows in Access SQL?

No, Access SQL does not support the multi-row VALUES syntax. Loop through your data and execute one INSERT per row, or use a recordset with AddNew.

How do I insert a date value?

Wrap the date in # signs, for example #12/31/2025#, and ensure the format matches your regional settings. Using the Format function with mm/dd/yyyy is safest.

What is the difference between CurrentDb.Execute and DoCmd.RunSQL?

CurrentDb.Execute runs the SQL without confirmation prompts and supports dbFailOnError for error handling. DoCmd.RunSQL may show prompts and is better for simple, interactive queries.

How do I insert a record and get its autonumber ID?

After executing the INSERT, run SELECT @@IDENTITY on the same database connection. Alternatively, use a recordset with AddNew and read the autonumber field after Update.

Why does my INSERT statement fail with a syntax error?

The most common cause is an unescaped apostrophe in a text value. Replace each single quote with two single quotes. Also check for missing commas and reserved words used as field names.

Can I insert data into a linked table?

Yes, provided the linked table is updatable and you have permissions. The same INSERT syntax applies, but errors may occur if the back-end is unavailable or the link is read-only.