Queries.Add creates a new query in Excel's Power Query collection from a VBA macro, which is what you use when a macro has to build or load a query definition on the fly rather than rely on one someone added by hand. The essential fact to get right: Queries.Add does not produce a data connection on its own. It adds a query object whose M language formula you then set, and you follow up with ListObjects.Add or with the query's own LoadTo behaviour to get a table or connection into the workbook. Labels and object names can differ slightly by Excel version and region, so adjust the exact wording where your ribbon differs.
What You'll Need
- A desktop copy of Excel with Power Query available (it is built in on modern Microsoft 365 and Excel 2016 and later builds; the Mac version supports it too, but some legacy data-source wizards differ).
- A workbook saved as .xlsm, since macros need the macro-enabled format.
- Access to the Developer tab so you can open the VBA editor and the Immediate window.
- Clear trust settings that let your own macros run, or a signed project, so the code is not blocked silently.
- At least one working load target in mind: a worksheet range, a table, or connection-only.
Step-by-Step
- Enable the Developer tab. Open Excel Options > Customize Ribbon and tick Developer in the right-hand list. Then click Developer > Visual Basic (or press Alt+F11) to open the editor.
- Insert a standard module. In the Project Explorer, right-click your workbook project, choose Insert > Module. Put test code there rather than in a sheet module, so it is easy to find again.
- Write a sub that references the query collection. The collection lives on the workbook object, so your line will look like
ThisWorkbook.Queries.Add Name:="MyQuery", Formula:=someMText. The name must be a short, unique string with no spaces if you plan to reference it later. - Build the M formula as a string. Pass the same text you would see in the Power Query Advanced Editor, for example . Because VBA strings use double quotes, double every internal quote ( "" ) so the M text stays valid. Store it in a variable first; debugging a long inline string is painful.
- Add the query, then load it. After
Queries.Addsucceeds, create a destination. The reliable pattern isThisWorkbook.Worksheets("Sheet1").ListObjects.Add(SourceType:=0, Source:=Array("OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$", "Location=" & queryName"), Destination:=Range("A1")).QueryTable.Refresh BackgroundQuery:=False. This binds the query to a real table so the data actually arrives. - Handle existing names. If a query with the same name exists, the add fails. Test first with a loop over the Queries collection and either skip or delete the old one (deleting removes its table too, so only do this deliberately).
- Run and verify. Press F5 with the cursor inside the sub, or use F8 to step line by line. Then close the editor and check that the table appears and that the query shows in the Queries & Connections pane (Data > Queries & Connections).
- Clean up and save. Save as .xlsm again, then reopen the file to confirm the query survives a close and open cycle. Queries added by code behave like hand-added ones after saving.
Common Mistakes
Forgetting the load step. The single most frequent error is expecting data to appear after Queries.Add alone. The query definition exists, but nothing is rendered until you add a QueryTable or use the load pattern above.
Unescaped quotes in the M string. M uses double quotes for text literals, and so does VBA. Every " inside the formula needs to be written as "" in VBA, or the string terminates early and you get a compile error.
Duplicate query names. Names are unique per workbook. Re-running a macro that adds the same name fails on the second run unless you check first.
Missing provider on the connection string. The Mashup OLE DB provider must be named exactly, and any typo in the connection or Location line usually surfaces as a refresh error rather than a clear message at add time.
Assuming it works identically everywhere. Workbook-level queries require desktop Excel. In shared or browser-based editing, macros do not run, so the query must already exist in the saved file for anyone opening it online.
Tips
Keep formulas small and composable: create helper queries with Queries.Add and reference them by name from a final query, mirroring how the Power Query editor structures steps. Store M text in a worksheet cell or a text file during development, then read it into a variable, so you can edit it without touching VBA code. Use a naming convention with a prefix (for example qry) and validate the name against ^[A-Za-z0-9_]+$ style rules to avoid problems later. Wrap the main body in error handling that reports the query name and the formula on failure, because Power Query errors are otherwise easy to misattribute. Finally, add a short comment above each Queries.Add call describing what the M text expects as input, so future edits do not break source references.
Troubleshooting
If the macro stops with a runtime error on the add line, check the name for spaces or duplicates, then check that the Formula argument is not empty. An empty formula adds a query that cannot evaluate.
If the query appears in the pane but the sheet stays empty, the load step is missing or its Destination range is invalid. Verify the sheet name is exact and the range is not protected.
If refresh fails with a provider error, re-check the connection string character by character, particularly the Provider=Microsoft.Mashup.OleDb.1 portion and the Location name matching the query name you just added.
If the query disappears after reopening the file, the workbook was probably saved without macros enabled or was recovered from a crashed state. Reopen the original .xlsm and confirm the macro ran to completion.
If nothing happens at all, macros may be disabled. Check Trust Center settings for macro notifications and enable content for this file. Deleting a query removes its loaded table, so back up the workbook before you remove anything in bulk.
Frequently Asked Questions
Does Queries.Add create a connection automatically?
No. It only adds the query definition. You must add a QueryTable or list object, or otherwise load it, to get a connection and visible data.
Can I use Queries.Add on Excel for the web?
No. VBA does not run in the browser version. Create the query on the desktop and save the file; it will open and refresh online where the data source allows it.
How do I add a query that only stores a connection?
Add the query, then create the connection without a destination range. The query remains refreshable from the Queries & Connections pane without creating a table.
Why does my formula need double quotes doubled?
Because both VBA and M use double quotes as text delimiters. Every internal quote must be escaped for VBA so the string reaches Power Query intact.
Can a macro edit an existing query?
Yes, by setting the query's Formula property after locating it in the Queries collection. Deleting and re-adding is an alternative, but it drops any loaded table.
Do queries added by code work in shared workbooks?
Only as stored in the saved file. Co-authoring with macros is limited, so verify the query still refreshes when others open the workbook.