Access VBA SQL INSERT: Step-by-Step Guide
In this article
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
- 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.)
- 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:
TheSub InsertOneRecord() Dim sql As String sql = "INSERT INTO Customers (FirstName, LastName, Age) " & _ "VALUES ('John', 'Smith', 30)" CurrentDb.Execute sql, dbFailOnError End SubdbFailOnErrorconstant makes Access raise a trappable error if the insert fails, instead of silently doing nothing. You can also useDoCmd.RunSQL sql, but it shows a confirmation prompt unless you setDoCmd.SetWarnings Falsefirst; remember to turn warnings back on. - 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:
Do this for every text value that comes from a form or user input.Dim name As String name = "O'Brien" name = Replace(name, "'", "''") sql = "INSERT INTO Customers (FirstName) VALUES ('" & name & "')" - 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:
If you use a date variable, format it explicitly:sql = "INSERT INTO Orders (OrderDate, Amount) VALUES (#12/31/2025#, 199.95)"Format(myDate, "\#mm\/dd\/yyyy\#"). - 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:
This avoids quote-escaping and protects against SQL injection if the database is shared.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 - 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.
- 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. - 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.RunSQLwithout 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 sqlbefore 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.Executefollowed bySELECT @@IDENTITYin the same session, or use a recordset with.AddNewand 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.