Who this lesson is for, and the problem with opening files
This lesson is for Excel users who already write some VBA and keep running into the same chore: the numbers you need live in another file. A sales export on a shared drive, last year's workbook, an Access database the operations team maintains, a table on a SQL Server. The usual macro opens that file, copies a big block of it into a staging sheet, closes it again and only then starts filtering and summing. It works, and in a small team it is often good enough. But it gets slower as the source grows, it fails when a colleague has the file open, and it runs whatever formulas and macros live inside the source.
ADO, short for ActiveX Data Objects, takes a different route. Instead of opening the file in Excel, your macro sends a SQL query to a database provider, the provider reads the file in the background, and only the rows and columns you asked for come back. In the free lab above, a macro builds a small sales workbook, closes it and then asks it a question in SQL, so ten rows are grouped down to three before anything reaches your sheet. This article explains why that matters, goes through the same example with every number, and shows you how to set up and test it on your own machine.
The core idea: send the question, not the file
Think of the two approaches as two ways of asking a colleague for a sales figure. Without ADO, you ask for the entire filing cabinet to be carried to your desk, then you look for the figure yourself. With ADO, you send a note saying "total per region, please" and get back a short answer. The work of finding, filtering and adding up happens at the source, in the database provider, and only the result travels.
Three pieces make this work. The connection says which provider to use and where the data is. For Excel and Access files that provider is the Microsoft ACE OLEDB provider, part of the Access Database Engine that comes with most Windows installations of Office. The query is ordinary SQL, where a worksheet is addressed as a table such as [Sales$]. The recordset is what comes back: a cursor over the result rows, which you can loop through or pour straight into a range with CopyFromRecordset.
Be clear about the platform before you invest time. ADO and the ACE provider are Windows technologies. Excel for Mac has neither, so a workbook built on ADO will not run there. On Windows, the most common setup problem is not your code but the provider: if Office is 64-bit and the installed Access Database Engine is 32-bit, or the other way round, you get "Provider cannot be found" although something is clearly installed. Lesson 2 of the course deals with that in detail.
A worked example: three regions from a closed file
The lab creates a workbook called Tabellab_AdoDemo.xlsx in your temp folder with one sheet named Sales. Row 1 holds the column names and rows 2 to 11 hold ten orders. These are fictional demo numbers, the same ones used across this VBA series, so you can compare results between courses.
| Row | A: Region | B: Product | C: Amount |
|---|---|---|---|
| 2 | Zurich | Keyboard | 89.90 |
| 3 | Bern | Monitor | 249.00 |
| 4 | Zurich | Mouse | 29.50 |
| 5 | Basel | Keyboard | 89.90 |
| 6 | Bern | Docking station | 179.00 |
| 7 | Zurich | Monitor | 249.00 |
| 8 | Basel | Mouse | 29.50 |
| 9 | Bern | Keyboard | 89.90 |
| 10 | Zurich | Docking station | 179.00 |
| 11 | Basel | Monitor | 249.00 |
The lab query is SELECT [Region], COUNT(*) AS Orders, SUM([Amount]) AS Total FROM [Sales$] WHERE [Region] IS NOT NULL GROUP BY [Region] ORDER BY SUM([Amount]) DESC. Read it as a sentence: from the Sales sheet, ignore empty rows, put the rows into one group per region, and for each group return the region, the number of orders and the sum of the amounts, largest total first. The provider does all of that, and the result is three rows. A small variation, keeping only orders above 100 and sorting by name, gives the second block of the table.
| Query | Region | Orders | Total |
|---|---|---|---|
| Lab query (all rows) | Zurich | 4 | 547.40 |
| Bern | 3 | 517.90 | |
| Basel | 3 | 368.40 | |
Variation: WHERE [Amount] > 100, ORDER BY [Region] | Basel | 1 | 249.00 |
| Bern | 2 | 428.00 | |
| Zurich | 2 | 428.00 |
It is worth checking an ADO result against ordinary formulas the first few times, so you trust the SQL. With the source workbook open, COUNTIFS and SUMIFS reproduce every number. There is a well-known catch, though: SUMIFS and COUNTIFS that point at a closed workbook return #VALUE! when Excel recalculates. SUMPRODUCT does work against a closed file, which is why it appears in the last row. The path in that formula is an example, so adjust it to where your file is.
| SQL part | Same answer with a formula (source open, sheet Sales) | Zurich |
|---|---|---|
COUNT(*) per region | =COUNTIFS(Sales!$A$2:$A$11,"Zurich") | 4 |
SUM([Amount]) per region | =SUMIFS(Sales!$C$2:$C$11,Sales!$A$2:$A$11,"Zurich") | 547.40 |
WHERE [Amount] > 100 | =SUMIFS(Sales!$C$2:$C$11,Sales!$A$2:$A$11,"Zurich",Sales!$C$2:$C$11,">100") | 428.00 |
| Same total from a closed file | =SUMPRODUCT(('C:\Data\[Sales.xlsx]Sales'!$A$2:$A$11="Zurich")*'C:\Data\[Sales.xlsx]Sales'!$C$2:$C$11) | 547.40 |
Here is a second macro you can paste below the lab code. It reuses the demo file the lab created, runs the variation with WHERE [Amount] > 100, and loops through the recordset instead of using CopyFromRecordset, so you see both styles. Like the lab, it uses late binding and declares the three ADO constants itself. It only reads from the source file and never changes or removes it. If you paste it into the same module as the lab, leave out the three Const lines and the Option Explicit line, because the lab already declares them.
Option Explicit
Private Const adOpenStatic As Long = 3
Private Const adLockReadOnly As Long = 1
Private Const adCmdText As Long = 1
Sub BigOrdersByRegion()
Dim conn As Object
Dim rs As Object
Dim sourcePath As String
Dim sql As String
#If Mac Then
MsgBox "ADO is not available in Excel for Mac.", vbExclamation
Exit Sub
#End If
sourcePath = Environ$("TEMP") & Application.PathSeparator & "Tabellab_AdoDemo.xlsx"
If Len(Dir(sourcePath)) = 0 Then
MsgBox "Run QueryAClosedWorkbook first. It creates the demo file.", vbExclamation
Exit Sub
End If
sql = "SELECT [Region], COUNT(*) AS Orders, SUM([Amount]) AS Total " & _
"FROM [Sales$] " & _
"WHERE [Amount] > 100 " & _
"GROUP BY [Region] " & _
"ORDER BY [Region]"
On Error GoTo Failed
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & sourcePath & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Set rs = CreateObject("ADODB.Recordset")
rs.Open sql, conn, adOpenStatic, adLockReadOnly, adCmdText
Do While Not rs.EOF
Debug.Print rs.Fields("Region").Value, rs.Fields("Orders").Value, _
Format$(rs.Fields("Total").Value, "#,##0.00")
rs.MoveNext
Loop
CleanUp:
On Error Resume Next
If Not rs Is Nothing Then rs.Close
If Not conn Is Nothing Then conn.Close
Set rs = Nothing
Set conn = Nothing
Exit Sub
Failed:
MsgBox "ADO error " & Err.Number & ": " & Err.Description, vbExclamation
Resume CleanUp
End Sub
Run it with F5 and open the Immediate window with Ctrl+G. You should see Basel 1 249.00, Bern 2 428.00 and Zurich 2 428.00. The structure is the one you will use in every ADO macro: build the SQL, open the connection, open the recordset, read it, and close both objects in a cleanup block that runs whether the query succeeded or not. The cleanup matters more than it looks. An ADO connection that is left open can keep the source file locked, so the next person who tries to save it gets a "file in use" message.
How to do it in Excel, step by step
- Make sure you are on Windows with desktop Excel. Check the bitness under File > Account > About Excel, where the first line ends in 32-bit or 64-bit.
- Save your workbook as Excel Macro-Enabled Workbook (*.xlsm) with File > Save As, so the code is kept.
- Press
Alt+F11to open the VBA editor and choose Insert > Module. - Paste the lab code with
QueryAClosedWorkbookand its helper functions. You do not need Tools > References, because the code usesCreateObject. - Put the cursor inside
QueryAClosedWorkbookand pressF5. The macro creates the demo file, queries it and writes three rows to a sheet calledAdoResult. - If you get "Provider cannot be found", install the Microsoft Access Database Engine redistributable in the same bitness as your Office, then run the macro again.
- Paste
BigOrdersByRegionbelow the lab code, leaving out its duplicateOption ExplicitandConstlines, then pressF8to step through it and watch each part run. - Change the SQL in small steps: a different
WHEREcondition,ORDER BY Total DESC, orAVG([Amount])instead ofSUM. Run it after each change so you know which edit caused a problem. - Check one result against a
SUMIFSformula with the source open, as in the table above, before you rely on a new query.
WHERE [Region] = 'Bern', and expect a few differences from other databases. Lesson 3 lists the ones that cause the most confusion.When to use ADO, and when not to
ADO is the right tool when a macro needs a precise slice of external data on demand: one month, one customer group, a total per region, taken from a file or database that is larger than the answer. It is less suitable when you need what a workbook looks like rather than what it contains, because ADO sees values only and ignores formatting, charts, comments and shapes. Merged cells and several header rows also confuse its guess at column names. And if the job is a scheduled refresh of a tidy table that people maintain without code, Power Query (Data > Get Data) is usually easier to hand over. Many teams use both: Power Query for standing refreshes, ADO inside macros that need a query built at run time.

Common mistakes, and how to spot them
- Querying the used range by accident.
[Sales$]means the sheet's used range, which can include hundreds of empty rows left behind by deleted data. Spot it whenCOUNT(*)is far larger than your real row count. AddWHERE [Region] IS NOT NULLor address an explicit rectangle such as[Sales$A1:C11]. - Wrong bitness of the provider. "Provider cannot be found" on a machine where the Access Database Engine is installed almost always means a 32-bit and 64-bit mismatch with Office.
- Forgetting the dollar sign or the brackets.
FROM Saleslooks for a named range called Sales, andFROM Sales Data$fails on the space. The safe form is always[Sheet Name$]. - Mixed data types in a column. The provider guesses each column's type from the first rows. If a column holds mostly numbers and a few text codes, the text values can come back as Null. Keep source columns clean, and see lesson 2 for the
IMEX=1option. - No cleanup on errors. If the macro stops between
conn.Openandconn.Close, the file can stay locked. Use a cleanup label that both the normal path and the error handler reach. - Expecting headers from CopyFromRecordset. It writes data only. Write the field names yourself from
rs.Fields(i).Name, as the lab does. - Building SQL from cell values by string concatenation. A name with an apostrophe breaks the query, and with a real database server this is how SQL injection happens. Lesson 7 shows how to use parameters instead.
Quick reference: objects, SQL and shortcuts used
| Item | Type | What it does |
|---|---|---|
CreateObject("ADODB.Connection") | VBA | Creates a connection without a library reference (late binding) |
conn.Open connString | VBA | Connects to the source named in the connection string |
Provider=Microsoft.ACE.OLEDB.12.0 | Connection string | The Access Database Engine provider that reads .xlsx, .xlsm, .xlsb and Access files |
Extended Properties="Excel 12.0 Xml;HDR=YES" | Connection string | Source is an .xlsx file, row 1 holds column names |
[Sales$] | SQL | A worksheet used as a table (its used range) |
[Sales$A1:C11] | SQL | An explicit rectangle on that sheet |
GROUP BY, COUNT(*), SUM() | SQL | Group rows and aggregate them in the driver |
rs.Open sql, conn, 3, 1, 1 | VBA | Runs the query: static cursor, read-only lock, text command |
rs.EOF, rs.MoveNext | VBA | End-of-data test and step to the next row |
Range("A2").CopyFromRecordset rs | VBA | Writes all remaining rows in one statement, without headers |
rs.Close, conn.Close | VBA | Releases the file lock, always in a cleanup block |
=SUMIFS(โฆ), =COUNTIFS(โฆ), =SUMPRODUCT(โฆ) | Formula | Used here to check the query result |
Alt+F11, F5, F8, Ctrl+G | Shortcut | VBA editor, run, step, Immediate window |
Real-world uses
- Monthly reporting from a large export. Pull only the current month and only the columns your report needs from a big sales workbook on a shared drive, without opening it and without waiting for its formulas to calculate.
- Reading a file someone else has open. Reading with ADO usually still works when a colleague has the workbook open, where
Workbooks.Openwould give you a read-only copy or a prompt. Test this with your own files and network setup. - Lookups against an Access database. A pricing or customer table maintained in Access can be queried directly from a quote template, so the template always uses current data.
- Summaries from SQL Server. With the right connection string and permission, the same pattern returns a grouped summary from a company database, and the server does the heavy lifting.
- Pre-aggregating before a PivotTable. When a source has far more rows than a report needs, a
GROUP BYquery brings in a compact summary that is quick to pivot and chart.
What you will build in the rest of this course
Lesson 1 is free. Lessons 2 to 8 are part of the paid course, available for a one-time $9.90, and each one comes with code you can run and adapt.
Connection Strings and Providers. You take the connection string apart for .xlsx, .xlsm, .xlsb, Access and SQL Server, read the Extended Properties properly, fix the bitness trap that causes "Provider cannot be found", and keep passwords out of your code.
Querying Another Workbook. You treat sheets and ranges as tables, write complete working queries, learn where the ACE SQL dialect differs from standard SQL, decode the common error messages and see how to query the workbook you are in.
Working With Recordsets. You move through results with EOF and MoveNext, read fields by name, choose a cursor type, handle Nulls safely and pull a whole result into an array with GetRows.
CopyFromRecordset and Writing Headers. You write tens of thousands of rows in one statement, add the headers it leaves out, guard against results that are too big for the sheet and turn the output into an Excel Table.
Access and SQL Server. You run the same code against an Access database, with joins and saved queries, and against SQL Server, including timeouts and the permissions you need.
Parameters, and Why Concatenation Is Dangerous. You see how gluing cell values into SQL breaks on an apostrophe and opens the door to SQL injection, and you replace it with a Command object and parameters.
Errors, Cleanup and Performance. You build an error handler that always closes the connection, read ADO's detailed error messages and pick up the habits that keep queries fast.
Summary
Opening another workbook to copy its data works, but it brings the whole file into Excel, runs its formulas and macros, and fails when the file is locked. ADO sends a SQL query to the ACE provider instead, which reads the closed file and returns only the result. In the lab, ten orders became three grouped rows, Zurich 547.40, Bern 517.90 and Basel 368.40, without the source ever being opened. ADO runs on Windows only, the provider must match the bitness of Office, and every connection must be closed in a cleanup block.
Now scroll up and run QueryAClosedWorkbook. Check that the three rows appear on the AdoResult sheet, compare one of them with a SUMIFS formula, then answer the check question about the used range. Once you have seen a closed file answer a question in SQL, the rest of the course shows you how to do the same with your own files, Access databases and SQL Server.
Frequently asked questions
How do I query a closed Excel workbook with VBA?
Create an ADODB.Connection with the Microsoft.ACE.OLEDB.12.0 provider and the file path in the connection string, then open a Recordset with a SQL query such as SELECT * FROM [Sales$]. The workbook is never opened in Excel.
What is ADO in Excel VBA?
ADO (ActiveX Data Objects) is a Microsoft data access library that lets VBA send SQL queries to data sources such as Excel files, Access databases and SQL Server. Results come back as a Recordset you can loop through or paste into a sheet.
Does ADO work in Excel for Mac?
No. ADO and the ACE OLEDB provider are Windows components, and Excel for Mac does not include them. A workbook that relies on ADO only runs on Windows.
Why do I get "Provider cannot be found" with Microsoft.ACE.OLEDB.12.0?
Either the Access Database Engine is not installed, or its bitness does not match Office, for example 32-bit engine with 64-bit Excel. Install the version that matches the bitness shown under File, Account, About Excel.
Why does my ADO query return many empty Null rows?
Naming a sheet as [Sheet$] returns its used range, which can still include rows whose contents were deleted. Filter them out with WHERE [Column] IS NOT NULL or query an explicit range such as [Sheet$A1:C11].
Is ADO faster than opening the workbook?
Often, especially when you need a small, filtered or grouped part of a large file, because only the result is transferred into Excel. For small files the difference may be negligible, so measure with your own data.
Keep going: External Data with SQL (ADO)
This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time โฌ9.90.
- Connection Strings and Providers
- Querying Another Workbook
- Working With Recordsets
- CopyFromRecordset and Writing Headers
- Access and SQL Server
- Parameters, and Why Concatenation Is Dangerous
- Errors, Cleanup and Performance