Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Power Query VBA: Automate Refreshes in Excel

· 6 min read · Home Automation

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can run Power Query from VBA, but the cleanest way is to refresh the queries and let VBA handle everything around them: opening the file, refreshing, saving a copy, and closing again. Power Query itself is built in the Power Query Editor, not in the VBA editor, so VBA cannot build or edit query steps directly. What VBA can do is trigger a refresh, wait for it to finish, and chain that refresh into a wider macro routine. The most reliable single line is ThisWorkbook.RefreshAll, which refreshes Power Query queries, data connections and PivotTables together. For finer control, loop through ThisWorkbook.Queries and refresh each connection by name.

What You'll Need

  • Excel for Windows or Mac with Power Query built in (Excel 2016 and later, and Microsoft 365). Power Query is on the Data tab; on older builds it may sit under a separate tab.
  • At least one query already loaded to a worksheet or the Data Model. VBA refreshes existing queries; it does not create them.
  • The workbook saved as .xlsm (macro-enabled), because a standard .xlsx cannot store VBA code.
  • The Developer tab visible, or press Alt+F11 to open the VBA editor directly.
  • External data sources reachable from the machine running the macro, with any credentials already stored in the workbook.

Step-by-Step

  1. Confirm your queries are loaded. Open the Data tab, click Queries & Connections, and check each query has a load destination (a table on a sheet or the Data Model). A connection-only query still refreshes, but you will not see the output anywhere.
  2. Save the workbook as macro-enabled. Use File > Save As and choose Excel Macro-Enabled Workbook (.xlsm). If you skip this, the code you write next is discarded on save.
  3. Open the VBA editor. Press Alt+F11. In the Project pane, right-click your workbook and choose Insert > Module. A module keeps the macro available to the whole workbook.
  4. Write the simplest refresh macro. Type the following into the module:
    Sub RefreshEverything()
        ThisWorkbook.RefreshAll
    End Sub
    This refreshes every Power Query query, connection and PivotTable cache in the workbook.
  5. Add a wait so the macro does not race the refresh. RefreshAll can return before background refreshes finish. Prevent that by turning off background refresh on each connection, or by adding a short wait loop. The robust approach is to set BackgroundQuery = False on each connection first, then refresh:
    Sub RefreshAndWait()
        Dim c As WorkbookConnection
        For Each c In ThisWorkbook.Connections
            On Error Resume Next
            c.OLEDBConnection.BackgroundQuery = False
            c.ODBCConnection.BackgroundQuery = False
            On Error GoTo 0
        Next c
        ThisWorkbook.RefreshAll
        Application.CalculateUntilAsyncQueriesDone
    End Sub
    CalculateUntilAsyncQueriesDone blocks until asynchronous queries complete, which is the safest way to know the data is current before the next line runs.
  6. Refresh a single query by name. If you only want one query updated, loop the queries collection and match on name:
    Sub RefreshOne()
        Dim q As WorkbookQuery
        For Each q In ThisWorkbook.Queries
            If q.Name = "SalesData" Then
                q.Formula = q.Formula
            End If
        Next q
    End Sub
    Reassigning the formula is a lightweight way to force a single query to re-evaluate without touching the rest. Replace SalesData with your exact query name, which is case-sensitive in practice.
  7. Run the macro. Press F5 in the editor, or return to Excel and use Developer > Macros, select the routine and click Run. Watch the status bar at the bottom of the window; it shows refresh progress.
  8. Chain the refresh into a wider routine. A typical pattern is refresh, then save a dated copy, then close:
    Sub RefreshAndArchive()
        RefreshAndWait
        ThisWorkbook.SaveCopyAs "C:\Reports\Report_" & Format(Date, "yyyy-mm-dd") & ".xlsx"
    End Sub
    SaveCopyAs writes a copy without changing the open file, so the workbook stays unsaved and reusable.
  9. Test with a deliberately broken source. Rename the source file or disconnect the network and run the macro. Confirm you get a visible error rather than a silent failure, then add error handling (see Troubleshooting).

Menu labels and the exact position of Power Query options differ slightly between Excel versions, platforms and regions, so treat the paths above as a guide rather than a fixed map.

Common Mistakes

  • Saving as .xlsx. The macro vanishes on close. Always use .xlsm.
  • Assuming RefreshAll has finished. Background queries can still be running when the next line executes, so you save stale data. Disable background refresh or use CalculateUntilAsyncQueriesDone.
  • Wrong query name. Names come from the Queries pane, not the output table name. A mismatch silently refreshes nothing.
  • Credentials not stored. A macro that works on your machine fails on a colleague's because the data source asks for sign-in. Store credentials in the workbook or use a source that does not prompt.
  • Refreshing on open plus a macro. If the workbook also refreshes on open, you refresh twice and slow everything down. Pick one method.
  • Expecting VBA to edit query steps. It cannot. Change steps in the Power Query Editor; use VBA only to trigger and orchestrate.

Tips

  • Keep the refresh routine in one module and call it from other macros, so there is a single place to fix problems.
  • Name queries clearly and without spaces; matching names in code is far easier.
  • Turn off background refresh permanently in the connection properties if the workbook is automated. It makes timing predictable.
  • Use Application.StatusBar to show progress text, then reset it to False at the end.
  • If the workbook is shared, refresh only what you need. Refreshing everything on a large model can take minutes.

Troubleshooting

The macro runs but data does not change. Check the query is loaded, not connection-only, and that the name in code matches exactly. Confirm the source itself has new data.

Runtime error 1004 on RefreshAll. Usually a protected sheet or a broken connection. Unprotect sheets the macro writes to, and open Queries & Connections to see which connection is flagged with an error.

It prompts for a password every run. Edit the connection's credentials and choose to save them in the workbook. If the source requires single sign-on, the prompt may be unavoidable on other machines.

Refresh hangs. A large source or a slow network is the usual cause. Test the source outside Excel, reduce columns and rows in the query, and avoid refreshing during other heavy work.

Errors after a source change. If a column was renamed upstream, the query steps break. Fix the step in the Power Query Editor, then rerun the macro.

Macros disabled. Check the Trust Center macro settings and ensure the file sits in a trusted location. Do not lower security settings globally just to run one file.

Frequently Asked Questions

Can VBA create a Power Query query from scratch?

Not through a supported, documented interface. Build queries in the Power Query Editor and use VBA to refresh and orchestrate them.

Does RefreshAll update Power Query queries?

Yes. It refreshes queries, data connections and PivotTable caches in the workbook, which is why it is the usual one-line answer.

Why does my macro finish before the refresh does?

Background refresh is enabled. Turn it off per connection or wait with CalculateUntilAsyncQueriesDone.

Can I refresh just one query?

Yes, by matching the query name in a loop over ThisWorkbook.Queries and forcing re-evaluation, rather than calling RefreshAll.

Does this work on Excel for Mac?

The core refresh methods work, but some connection properties and the VBA editor differ. Test on the target machine before relying on it.

Will the macro run when the workbook opens?

Only if you place the call in the workbook's Open event. Otherwise run it manually or from a button.