Smart Systems for Home

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

VBA Access Insert Values into Table using SQL

· 6 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 values into a Microsoft Access table using VBA, you use the INSERT INTO SQL statement executed via the CurrentDb.Execute method or the DoCmd.RunSQL command. The most efficient approach is CurrentDb.Execute because it bypasses the standard Access confirmation prompts and allows for better error handling through the dbFailOnError option. This method allows you to programmatically move data from forms, variables, or other tables into a target table without manual entry.

What You'll Need

  • Microsoft Access installed with a database file (.accdb or .mdb).
  • A destination table already created with defined fields and data types.
  • Access to the Visual Basic for Applications (VBA) editor.
  • Basic familiarity with SQL syntax for the INSERT INTO command.

Step-by-Step

  1. Open the VBA Editor: Open your Access database. Press Alt + F11 on your keyboard to open the Visual Basic Editor. From the top menu, go to Insert > Module to create a new standard module where your code will reside.
  2. Declare Your Variables: Before writing the SQL string, declare variables to hold the data you wish to insert. This ensures that the data types match the table fields. For example, if you are inserting a customer name (text), an order date (date), and a quantity (number), declare them as String, Date, and Integer respectively.
  3. Construct the SQL String: The INSERT INTO statement follows a specific pattern: INSERT INTO TableName (Field1, Field2, ...) VALUES (Value1, Value2, ...). Because you are building this string in VBA, you must use concatenation (the & operator) to include your variables. Crucially, you must format the values based on their data type:
    • Text: Must be enclosed in single quotes (e.g., 'Value').
    • Dates: Must be enclosed in hash signs (e.g., #2023-12-25#).
    • Numbers: No delimiters are required.
  4. Write the Execution Code: Use CurrentDb.Execute to run the command. This is preferred over DoCmd.RunSQL because it does not trigger the "You are about to append 1 row" warning box. Use the dbFailOnError constant to ensure that if the insert fails (due to a constraint or data type mismatch), VBA will throw a runtime error that you can catch.
  5. Implement Error Handling: Wrap your execution code in an On Error GoTo block. This prevents the application from crashing if the database is locked or if a primary key violation occurs (e.g., trying to insert a duplicate ID).
  6. Test with Debug.Print: Before executing the SQL, use Debug.Print strSQL. This prints the final generated SQL string to the Immediate Window (Ctrl + G), allowing you to copy and paste it directly into a standard Access Query window to verify the syntax is correct.

Example Code for a Single Record:

Sub InsertSingleRecord()
    Dim db As DAO.Database
    Dim strSQL As String
    Dim varName As String
    Dim varDate As Date
    Dim varAmount As Double

    Set db = CurrentDb
    
    ' Sample data
    varName = "John Doe"
    varDate = Date
    varAmount = 150.50

    ' Constructing the SQL string
    ' Note the single quotes for text and hashes for dates
    strSQL = "INSERT INTO tblOrders (CustomerName, OrderDate, TotalAmount) " &
              "VALUES ('" & varName & "', #" & varDate & "#, " & varAmount & ")"

    Debug.Print strSQL ' Check syntax in Immediate Window

    On Error GoTo ErrHandler
    db.Execute strSQL, dbFailOnError
    MsgBox "Record inserted successfully!", vbInformation

ExitSub:
    Set db = Nothing
    Exit Sub

ErrHandler:
    MsgBox "Error: " & Err.Description, vbCritical
    Resume ExitSub
End Sub

Example Code for Bulk Insertion (from another table):

If you need to insert all values from one table into another, you do not need a loop. You can use the INSERT INTO ... SELECT syntax, which is significantly faster.

Sub BulkInsertData()
    Dim strSQL As String
    ' This inserts all records from tblTemp into tblFinal where the status is 'Complete'
    strSQL = "INSERT INTO tblFinal (CustomerName, OrderDate, TotalAmount) " &
              "SELECT CustomerName, OrderDate, TotalAmount FROM tblTemp " &
              "WHERE Status = 'Complete'"
    
    CurrentDb.Execute strSQL, dbFailOnError
    MsgBox "Bulk transfer complete!"
End Sub

Common Mistakes

  • Missing Spaces: A very common error is forgetting to put a space at the end of a line when concatenating strings. For example, "INSERT INTO Table" & "VALUES..." results in "INSERT INTO TableVALUES...", which causes a syntax error.
  • Incorrect Quote Nesting: Mixing double quotes and single quotes can be confusing. Remember that the SQL engine needs single quotes for text values, while VBA needs double quotes to define the string itself.
  • Reserved Word Conflicts: Using field names like Date , Order , Name , or Value will cause the SQL statement to fail. If your fields use these names, you must enclose them in square brackets, such as .
  • Wrong Date Formats: Access SQL expects dates in US format (MM/DD/YYYY) or ISO format (YYYY-MM-DD). Using regional formats (like DD/MM/YYYY) inside a SQL string can lead to dates being swapped or rejected.

Tips

  • Use the Immediate Window: Always Debug.Print your SQL string. It is much easier to spot a missing comma or quote in the Immediate Window than it is to guess based on a generic "Syntax Error" message.
  • Avoid DoCmd.RunSQL: Unless you specifically want the user to see the Access system warnings, avoid DoCmd.RunSQL. CurrentDb.Execute is cleaner, faster, and more professional.
  • Handle Nulls: If a variable might be empty, you cannot simply concatenate it. You may need a helper function to check if the variable IsNull and replace it with the word NULL (without quotes) in the SQL string.
  • Transaction Control: For complex inserts involving multiple tables, consider using DBEngine.BeginTrans and DBEngine.CommitTrans. This ensures that if one insert fails, none of the changes are saved, maintaining data integrity.

Troubleshooting

If your code does not go to plan, follow these steps in order:

  1. Check the Immediate Window: Copy the printed SQL string and paste it into a new Query in Access (switch to SQL View). Run the query. Access will often give a much more specific error message than VBA does.
  2. Verify Field Names: Ensure the field names in your INSERT INTO clause exactly match the names in the table design. A single typo will result in a "Too few parameters. Expected X" error.
  3. Check Data Types: Ensure you aren't trying to insert a string into a numeric field or a number into a date field. This will trigger a "Type Mismatch" error.
  4. Check for Locked Records: If the table is open in exclusive mode or a record is being edited by another user, the Execute method may fail. Close all open tables and try again.
  5. Verify Primary Keys: If your table has a Primary Key (like an ID field) that is not an AutoNumber, ensure you are providing a unique value. Attempting to insert a duplicate ID will cause a "Key Violation" error.

Frequently Asked Questions

How do I handle AutoNumber fields during an insert?

You should omit AutoNumber fields from your INSERT INTO field list and the VALUES list. Access automatically generates the unique ID for you when the record is created.

Can I insert values from an Excel sheet using this method?

While you can loop through Excel cells and use INSERT INTO, it is much slower. For bulk Excel imports, it is better to use DoCmd.TransferSpreadsheet to bring the data into a temporary table, then use an INSERT INTO ... SELECT query to move it to the final table.

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

DoCmd.RunSQL is a macro-style command that triggers built-in Access warnings (e.g., "You are about to append 1 row"). CurrentDb.Execute is a DAO method that runs silently and is generally faster and more robust for professional applications.

How do I insert a value that contains a single quote (like O'Reilly)?

Single quotes in data will break your SQL string. To fix this, use the Replace function to double the single quotes: Replace(varName, "'", "''"). This tells SQL that the second quote is part of the text, not the end of the string.

Can I insert multiple rows in a single SQL statement?

Unlike some other SQL dialects (like MySQL or SQL Server), Microsoft Access does not support inserting multiple rows using a single VALUES clause (e.g., VALUES (1, 'A'), (2, 'B')). You must either execute the INSERT INTO statement multiple times in a loop or use an INSERT INTO ... SELECT statement.