VBA Insert Into SQL: Step-by-Step Guide
In this article
To insert data from Excel into a SQL Server table using VBA, you need an ADO connection and a parameterized INSERT statement. The shortest working approach is: add a reference to Microsoft ActiveX Data Objects, open a connection with a connection string, build an INSERT INTO statement with parameters, and execute it. This guide walks through each step, including how to avoid SQL injection and handle common errors.
What You'll Need
- Excel (or another Office app that supports VBA) with the Developer tab enabled.
- Access to a SQL Server database, plus a login that has INSERT permission on the target table.
- The server name, database name, and table name. If you use Windows authentication, your Windows account must be authorized; if you use SQL authentication, you need a username and password.
- Basic familiarity with the VBA editor (Alt+F11).
Step-by-Step
- Enable the Developer tab. In Excel, go to File > Options > Customize Ribbon and check Developer in the right-hand list. Click OK. (Menu labels can differ slightly by version and region.)
- Open the VBA editor and add a reference. Press Alt+F11. In the editor, go to Tools > References and tick Microsoft ActiveX Data Objects 6.1 Library (or the highest version listed). Click OK. This lets you use ADODB objects without late binding.
- Insert a new module. In the VBA editor, right-click your project in the Project Explorer, choose Insert > Module. All code below goes into this module.
- Write a subroutine that opens a connection. Use a connection string like this for Windows authentication:
Provider=SQLOLEDB;Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=SSPI;
For SQL authentication, replaceIntegrated Security=SSPIwithUser ID=YourUser;Password=YourPassword;. Store credentials securely; do not hard-code passwords in shared workbooks. - Build the INSERT statement with parameters. Never concatenate cell values directly into SQL. Use
?placeholders and an ADODB.Command object with parameters. Example:Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandText = "INSERT INTO Customers (Name, Email) VALUES (?, ?)"
cmd.Parameters.Append cmd.CreateParameter("Name", adVarWChar, adParamInput, 100, Range("A2").Value)
cmd.Parameters.Append cmd.CreateParameter("Email", adVarWChar, adParamInput, 255, Range("B2").Value)
cmd.Execute - Loop through rows if needed. Wrap the command execution in a
For EachorFor i = 2 To LastRowloop, updating the parameter values each time. Reuse the same Command object for speed. - Close and clean up. After the loop, call
conn.CloseandSet conn = Nothing. This releases the connection and avoids locking issues. - Test with a single row first. Run the subroutine on one row and verify the data appears in SQL Server using a SELECT query. Then expand to the full range.
Common Mistakes
- Concatenating values into SQL. This invites SQL injection and breaks on apostrophes. Always use parameters.
- Forgetting to set the parameter size. For string parameters, specify a length (e.g., 100) or the provider may truncate or error.
- Using the wrong data type. Numbers should use
adIntegeroradDouble; dates useadDate. Mismatches cause conversion errors. - Leaving the connection open. This can lock tables and exhaust connection pools. Always close in a cleanup block, even on error.
- Assuming the table schema. Column names and order must match your INSERT statement. Check the actual table design in SQL Server Management Studio.
Tips
- Use early binding (the reference from Step 2) for IntelliSense and better performance; late binding (
CreateObject("ADODB.Connection")) avoids reference issues on other machines. - Wrap the main code in
On Error GoToand log the error number and description to a cell or text file. - For large datasets, consider batching inserts in a transaction:
conn.BeginTransbefore the loop andconn.CommitTransafter, with rollback on error. - Test your connection string separately using a small VBA snippet that runs
SELECT 1before attempting inserts.
Troubleshooting
If you get a "Login failed" error, check the authentication mode: Windows authentication requires your Windows account to have a SQL login; SQL authentication requires the exact username and password, and mixed mode must be enabled on the server. A "Cannot find table" error usually means the database name is wrong or the table is in a different schema (e.g., dbo). Use the fully qualified name dbo.Customers. If you see "Incorrect syntax near '?'", you are likely using a provider that does not support parameter placeholders in that position; switch to SQLOLEDB or MSOLEDBSQL. For "String or binary data would be truncated", a value exceeds the column length; check the parameter size and the column definition. If the code runs but no rows appear, ensure you are not rolling back a transaction or that the INSERT is not inside a loop that never executes. Finally, if the macro is slow, disable screen updating and set calculation to manual while it runs.
Frequently Asked Questions
Can I insert into SQL Server from Excel without a reference?
Yes, use late binding: Dim conn As Object: Set conn = CreateObject("ADODB.Connection"). This avoids setting a reference but loses IntelliSense.
How do I insert multiple rows at once?
Either loop with a parameterized command (recommended for safety) or build a single INSERT with multiple VALUES clauses. Looping is simpler and avoids SQL injection risks.
Why do I get "Provider cannot be found"?
The OLEDB provider may not be installed. Try MSOLEDBSQL (Microsoft OLE DB Driver for SQL Server) or SQLNCLI11. Install the driver from Microsoft if needed.
Can I use this with Azure SQL Database?
Yes, use a connection string with Server=tcp:yourserver.database.windows.net,1433;Database=yourdb;User ID=...;Password=...;Encrypt=True; and ensure your client IP is allowed in the firewall.
How do I handle NULL values?
Set the parameter value to Null (VBA) and use adParamInput with a variant type. For strings, DBNull.Value is not directly available in VBA; use Null and ensure the column allows NULLs.