You can insert rows from Excel into a SQL database with VBA by opening an ADO connection, building an INSERT INTO statement, and running it with Connection.Execute. The safest approach is a parameterized command (an ADODB.Command with a parameter and a ?param placeholder), which avoids quoting problems and blocks SQL injection. This guide uses the Microsoft ActiveX Data Objects library (ADO, usually version 6.1 on modern Office) and targets a SQL Server database; the same pattern works for Access with minor changes to the connection string.

What You'll Need

  • Excel with the VBA editor available (Alt+F11 opens it; some corporate builds disable macros, so confirm they are allowed).
  • A reference to Microsoft ActiveX Data Objects 6.1 Library (in the VBA editor: Tools > References). Labels in menus and dialogs can differ slightly by Office version, so look for the closest match.
  • Network access from your machine to the SQL Server, plus a login with INSERT permission on the target table.
  • The server name, database name, table name, and the exact column names and data types of the target table. Data types matter: a text value sent to an int column fails.
  • A test table or a backup of the production table, because mistakes here write real data.

Step-by-Step

  1. Inspect the target table first. In SQL Server Management Studio run SELECT TOP 10 * FROM dbo.YourTable and note which columns are required (NOT NULL with no default), which are identity columns (you cannot insert into those unless identity insert is explicitly enabled), and the type of each column. Also note whether the table has a unique key that could reject duplicate inserts.
  2. Add the library reference. In the VBA editor choose Tools > References and tick Microsoft ActiveX Data Objects 6.1 Library. If it is missing, install it from the Office or MDAC package rather than hunting for random downloads. Without the reference, ADODB types will not resolve and the code will not compile.
  3. Declare your variables. You need an ADODB.Connection, an ADODB.Command, and an ADODB.Parameter. Declare them with Dim at the top of the procedure so you can clean them up reliably at the end.
  4. Build the connection string. A typical SQL Server string looks like Provider=MSOLEDBSQL;Server=myserver;Database=mydb;Trusted_Connection=Yes; for Windows authentication, or replace the last part with User ID=myuser;Password=mypass;. Prefer Windows authentication where possible so no password sits in the workbook. If the OLE DB driver is not installed, the provider name may need to change; ask your DBA which driver your site standardizes on.
  5. Open the connection. Call conn.Open connString inside error handling. A failed open is the most common failure point, usually from a wrong server name, a disabled TCP/IP protocol, or a firewall rule.
  6. Create the command and attach it. Set cmd.ActiveConnection = conn and cmd.CommandType = adCmdText. Use adCmdText for ad-hoc SQL and adCmdStoredProc if you are calling a stored procedure instead.
  7. Write the parameterized SQL. The text is INSERT INTO dbo.Customers (Name, City, Amount) VALUES (?, ?, ?). The question marks are placeholders filled in order, so the order of your parameter additions must match the order of the columns.
  8. Add parameters with explicit types and sizes. For each placeholder use cmd.Parameters.Append cmd.CreateParameter("Name", adVarWChar, adParamInput, 50, ws.Cells(i, 1).Value). Give text parameters a size at least as large as the column; too small a size truncates the value silently in some drivers. Use adInteger, adDouble, adCurrency or adDBTimeStamp for numbers and dates, and convert empty cells to Null rather than passing empty strings to numeric columns.
  9. Execute the command. Call cmd.Execute. For a plain insert you do not need a recordset. If you need the new identity value back, use SELECT SCOPE_IDENTITY() in a separate command executed on the same connection.
  10. Loop over your data range. Read the range into a Variant array with data = ws.Range("A2:C100").Value and loop over the array instead of reading cell by cell; it is dramatically faster over hundreds or thousands of rows.
  11. Clean up. Set each object to Nothing and close the connection in the same error-handling block. Leaving connections open exhausts the connection pool and can lock tables.
  12. Test small and verify. Run it against one or two rows, then check the table with a SELECT. Only then scale to the full dataset, ideally inside a transaction so a mid-run failure rolls everything back.

Common Mistakes

  • Building SQL by concatenation. Strings like "INSERT INTO t VALUES ('" & cell & "')" break on apostrophes (O'Brien) and open the door to SQL injection. Always parameterize.
  • Parameter order mismatch. Parameters bind by position, not name. Mixing the order silently writes values into the wrong columns.
  • Forgetting the library reference. The code compiles fine on the author's machine and fails on a colleague's because the reference is missing.
  • Passing empty strings to numeric or date columns. Convert blanks to Null explicitly, or the insert fails with a conversion error.
  • Inserting into identity columns. If the table auto-generates a key, omit that column from the insert list entirely.
  • No error handling. A single bad row stops the loop with a cryptic message; wrap each insert or use a transaction so you know exactly where it failed.

Tips

  • Store the connection string in a hidden sheet or a settings cell rather than hard-coding it in dozens of procedures.
  • Use a stored procedure for repeated inserts; it centralizes validation and is easier for a DBA to audit.
  • Batch inserts with a single multi-row VALUES list for large volumes, or use a table-valued parameter if your setup supports one.
  • Log each success and failure to a worksheet column so you can re-run only the failed rows.
  • Turn off screen updating during the loop to keep the UI responsive.

Troubleshooting

If the connection will not open, check the server name spelling, confirm SQL Server allows remote connections, and ask whether the firewall permits the port. If you get a login error, verify the account has access to that database specifically, not just the server. If a "provider not registered" error appears, the OLE DB driver is missing or the name in the connection string is wrong. If execution returns a syntax error near a quote, you likely concatenated a value containing an apostrophe. If you see a truncation or conversion error, re-check parameter sizes and types against the column definitions. If the insert reports success but no rows appear, confirm you committed the transaction and are querying the same database and schema, and check for a trigger that might roll back the insert. If it works for one row but fails in bulk, a later row probably violates a NOT NULL or unique constraint; wrap the loop in a transaction and inspect the failing row.

Frequently Asked Questions

Can I insert into SQL Server without ADO?

Yes, but ADO is the most common and best-documented route from VBA. DAO works well with Access databases but is not suitable for SQL Server.

How do I get the new row's identity value?

Execute a second command on the same connection running SELECT SCOPE_IDENTITY() and read the returned value immediately after the insert.

Why does my loop run slowly?

Reading cells one at a time is the usual cause. Load the range into an array first, and consider batching inserts or using a stored procedure.

Can I roll back a failed bulk insert?

Yes. Begin a transaction on the connection before the loop, commit when it finishes, and roll back in the error handler so partial data is not left behind.

Does this work with Access databases?

The same pattern works; change the provider in the connection string to the Access OLE DB provider and point to the .accdb file.