.Execute is the ADODB.Command method you use in Excel VBA to send a SQL statement to a data source and run it without expecting rows back. It is the quickest way to update, insert, delete or run action queries against Access, SQL Server or any OLE DB source from inside Excel. If you need to read data (a SELECT), .Execute still works, but you capture the returned recordset instead of ignoring it. This guide covers wiring up a connection, building the command, running it and reading the results, plus the errors that trip most people up. Note that menu labels and dialog wording can differ slightly by Office version, device or region, so where a button is named below, treat it as a signpost rather than an exact string.

What You'll Need

  • Excel on Windows or Mac with the Visual Basic Editor (Alt+F11 on Windows, Option+F11 on Mac). ActiveX Data Objects (ADO) are built into Office, so no add-in download is needed.
  • A target data source you have permission to read or write: an Access database file, a SQL Server instance, or another OLE DB provider.
  • A connection string or a saved connection. For Access files, the ACE provider (Microsoft.ACE.OLEDB.12.0) is the current one; the older JET provider only suits very old mdb files.
  • Macro-enabled workbook format (.xlsm) so your code is kept: File > Save As and pick Excel Macro-Enabled Workbook.
  • Trust settings that allow macros to run. Macros are blocked in files from the internet until you unblock them, so check File > Info and, if prompted, enable editing/content for your own trusted file.
  • The Microsoft Access Database Engine installed if you connect to Access files from a machine without Access. Install only the official download from Microsoft.

Step-by-Step

  1. Add references (optional but tidy). In the VBA Editor open Tools > References and tick Microsoft ActiveX Data Objects (the highest listed library is fine). Alternatively use late binding by declaring everything as Object, which avoids reference version problems when sharing the file. Late binding is the safer choice for files that travel between machines.
  2. Declare your objects. You need a connection, a command and optionally a recordset. For late binding: Dim cn As Object, cmd As Object, rs As Object. For early binding, declare ADODB.Connection, ADODB.Command and ADODB.Recordset.
  3. Build the connection string. For an Access file: Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Data\Sales.accdb;. Note the double backslashes in VBA string literals, or join a variable path. For SQL Server, the official pattern is Provider=MSOLEDBSQL;Server=myserver;Database=mydb;Trusted_Connection=Yes; so Windows authentication is used and no password sits in code.
  4. Open the connection. Set cn = CreateObject("ADODB.Connection"), then cn.Open connString. Put this in error handling because a wrong path or a locked database fails here first (see Troubleshooting).
  5. Create the command object. Set cmd = CreateObject("ADODB.Command"), then Set cmd.ActiveConnection = cn. Assign cmd.CommandType = 1 for plain text SQL (the adCmdText constant) so the provider treats your string as a statement rather than a stored procedure name.
  6. Write the SQL and quote it safely. Put the statement in cmd.CommandText. Never concatenate raw cell text into SQL. Use parameters instead: cmd.CommandText = "UPDATE Customers SET Phone = ? WHERE ID = ?", then cmd.Parameters.Append cmd.CreateParameter("Phone", 202, 1, 50, txtPhone.Value). Parameter type 202 is text and 1 means input; add one parameter per ? in the same order. This prevents broken statements when a value contains an apostrophe and closes off SQL injection.
  7. Call .Execute for an action query. cmd.Execute is enough for UPDATE, INSERT, DELETE or a stored procedure. To know how many rows changed, capture the return value: Dim n As Long: n = cmd.Execute. The number is provider-dependent and some sources return -1, so treat it as information, not a guarantee.
  8. Call .Execute for a SELECT and capture the recordset. Set rs = cmd.Execute, then loop with Do Until rs.EOF and read fields as rs.Fields("Name").Value, calling rs.MoveNext each pass. Copy values to a worksheet cell or an array row inside the loop.
  9. Close everything in reverse order. rs.Close (if used), Set rs = Nothing, cn.Close, Set cn = Nothing, Set cmd = Nothing. Leaving connections open locks Access files and holds server sessions, which causes failures next run.
  10. Wrap it in error handling. Add On Error GoTo Cleanup near the top and a Cleanup: label at the end that closes the connection whether the code succeeded or not. Without this, one bad run leaves a locked file behind.

Common Mistakes

  • Forgetting the semicolon at the end of an Access connection string, which produces an unhelpful "not a valid file name" error.
  • Using the ACE provider in a 64-bit Office install when a 32-bit-only engine is installed, or vice versa. The bitness of the provider must match Office.
  • Leaving out Set cmd.ActiveConnection = cn and getting "Object required" or a command with no connection.
  • Concatenating text into SQL and then breaking on apostrophes or letting user text run as code.
  • Using .Execute for a SELECT and then referring to the connection while the recordset is still open: a second execute over the same open connection can fail on some providers. Finish, read or close the first recordset.
  • Assuming the return value is always the row count. For rows-affected feedback, provider and statement type matter.
  • Pointing at a workbook-relative path that changes when the file is saved elsewhere. Build paths from ThisWorkbook.Path.

Tips

  • Keep connection strings in a single helper function so one edit updates every procedure.
  • Test your SQL in Access's query design or in your database tool first, then paste it into CommandText. Debugging SQL inside VBA is far slower.
  • For large imports use rs.GetRows to pull the whole result into an array in one call, then write it to the sheet with Range.Value in a single step rather than one cell at a time.
  • Run destructive statements (UPDATE, DELETE) against a copy of the data first and confirm the WHERE clause is present.
  • Use WithEvents-free late binding if the file is shared, so missing references never break it on another PC.

Troubleshooting

"Provider cannot be found": the ACE engine is missing or the wrong bitness. Install the official Microsoft Access Database Engine matching your Office build, or switch to the correct provider name.

"Could not find file" or "not a valid password": the database path is wrong, the file is open exclusively elsewhere, or the file is password-protected. Close the other program and confirm the path exists with Dir() before opening.

"Operation must use an updateable query": the folder holding an Access file is read-only, or the file sits on a network share without write permission. Move it to a folder you control. This is the most common permission failure.

SQL Server login failed: trusted connections need the workbook's user to have database rights. Try a server login the administrator has given you, without embedding it in the workbook.

Recordset is empty or fields error: check that column names match exactly, including spaces and capitals, and that you used the right table. Print cmd.CommandText to the Immediate window with Ctrl+G to inspect what actually ran.

If that did not work, reduce the problem: run a trivial SELECT 1 through the same connection. If that succeeds, the connection is fine and the fault is in your SQL or parameters.

Frequently Asked Questions

What is the difference between .Execute and opening a recordset directly?

.Execute runs a statement and returns a recordset only if rows come back. Opening a recordset with cn.Open "SELECT ..." or a separate Recordset object gives you explicit control over cursor and lock type, which is useful for editing rows. Use .Execute for action queries and quick reads, a Recordset object for anything you intend to edit row by row.

Can I run a SELECT with .Execute?

Yes. Capture the return value with Set rs = cmd.Execute and loop through it. You cannot have two active result sets from the same command object, so finish one before starting the next.

Does VBA in Excel online or on a Mac support .Execute?

Excel for the web does not run VBA macros. Excel for Mac runs VBA, but the database providers available differ from Windows, so a connection string built around ACE may work while a Windows-only SQL Server provider library does not. Test on the platform you will actually use.

How do I get the number of rows affected?

Assign the result of cmd.Execute to a variable. Many providers return the count for INSERT, UPDATE and DELETE, but some return -1, especially when the statement includes certain options. If you need a reliable count, run a follow-up SELECT with a matching WHERE clause.

Is it safe to put an Access password in a connection string?

It works, but the password sits in plain text in the workbook for anyone who opens it. Prefer Windows authentication or a trusted connection where the source supports it, and restrict who can edit your VBA project.

Can .Execute run a stored procedure?

Yes. Set CommandType to the stored procedure constant (4), name the procedure in CommandText, add parameters through the Parameters collection, then call Execute. Some providers expect the bare procedure name, while others accept an EXEC statement, so follow the provider's documentation.