Excel VBA Refresh Power Query: Step-by-Step Guide
In this article
To refresh a Power Query in Excel using VBA, use the ActiveWorkbook.RefreshAll method to update all data connections, or target a specific query using ActiveWorkbook.Connections("Query - YourQueryName").Refresh. This automation removes the need to manually click the Refresh button in the Data tab, allowing you to trigger data updates based on a button click, a cell change, or a scheduled workbook event.
What You'll Need
- Microsoft Excel installed on Windows (VBA is not available in Excel for Web).
- An existing Power Query already loaded into the workbook (either as a Table or a Connection Only).
- The Developer tab enabled in the Excel Ribbon.
- The exact name of the query you wish to refresh (if you are not refreshing all queries).
Step-by-Step
- Enable the Developer Tab: If you do not see the Developer tab at the top of your screen, right-click any existing tab on the Ribbon, select Customize the Ribbon, and check the box for Developer in the right-hand column. Click OK.
- Open the Visual Basic Editor: Click the Developer tab and select the Visual Basic button, or press
Alt + F11on your keyboard. This opens the VBE window where your code will live. - Insert a New Module: In the VBE, go to the Insert menu and select Module. This creates a blank space where you can write your macros. It is better to use a module than to write code directly into a Sheet or ThisWorkbook object for general utility macros.
- Write the Refresh Code: Depending on your goal, enter one of the following code snippets into the module window:
- Option A: Refresh Everything. Use this if you have multiple queries and want them all updated at once:
Sub RefreshAllQueries() ActiveWorkbook.RefreshAll End Sub - Option B: Refresh a Specific Query. Use this to avoid the overhead of refreshing unrelated data. Replace "Query - MyData" with the actual name of your connection:
Sub RefreshSpecificQuery() ActiveWorkbook.Connections("Query - MyData").Refresh End Sub
- Option A: Refresh Everything. Use this if you have multiple queries and want them all updated at once:
- Disable Background Refresh: This is a critical technical step. By default, Power Query refreshes in the background, meaning the VBA code continues to run while the data is still loading. This often causes errors if your next line of code depends on the new data. To fix this:
- Go back to the Excel sheet.
- Go to the Data tab > Queries & Connections.
- Right-click your query in the side pane and select Properties.
- Uncheck the box that says "Enable background refresh".
- Click OK.
- Assign the Macro to a Button: To make the refresh easy for users, go to the Developer tab, click Insert, and choose the Button (Form Control). Draw the button on your sheet. When the "Assign Macro" window pops up, select the macro you just wrote (e.g., RefreshAllQueries) and click OK.
- Save as Macro-Enabled Workbook: Save your file with the
.xlsmextension. Standard.xlsxfiles cannot store VBA code and will delete your macro upon closing.
Common Mistakes
One of the most frequent errors is forgetting to disable the "Background Refresh" setting. If this is enabled, VBA triggers the refresh and immediately moves to the next line of code. If your macro is designed to perform calculations or export a PDF based on the refreshed data, it will use the old data because the query is still running in the background. Always disable background refresh for any query involved in a VBA sequence.
Another common mistake is using the wrong connection name. In the VBA editor, the connection name is usually prefixed with "Query - ". If your query is named "SalesData", the VBA reference must be "Query - SalesData". If you omit the prefix, Excel will return a "Subscript out of range" error because it cannot find a connection with that exact string.
Users also frequently forget to save the file as an .xlsm. This is a frustrating error where the code works perfectly during the session, but the user discovers the next morning that the button no longer works because the macros were stripped out during the save process.
Tips
To make your workbook feel more professional, you can add a simple notification to let the user know the refresh is happening. Since Power Query can take several seconds or minutes, the screen may appear frozen. Use Application.StatusBar = "Refreshing data, please wait..." at the start of your code and Application.StatusBar = False at the end to provide a visual cue in the bottom-left corner of the Excel window.
If you want the refresh to happen automatically when the workbook opens, you can place the refresh command inside the Workbook_Open event. To do this, double-click "ThisWorkbook" in the VBE project explorer and paste your refresh code inside the Private Sub Workbook_Open() block. This ensures the user always sees the most current data without having to click a button.
For advanced users, you can use a loop to refresh multiple specific queries without refreshing the entire workbook. This is useful if you have some queries that are very slow and others that are fast. You can create an array of connection names and use a For Each loop to iterate through them, providing more control over the update sequence.
Troubleshooting
If you encounter a "Subscript out of range" error, the first thing to check is the spelling of your query name. Go to the Data tab > Queries & Connections and verify the exact name. Remember that VBA is case-sensitive for these strings. Ensure you have included the "Query - " prefix in your code.
If the macro runs but the data does not actually change, check your data source. Power Query may be pointing to a file path that has changed or a database that is currently offline. Try refreshing the query manually via the Ribbon; if the manual refresh fails, the issue is with the query connection, not the VBA code.
If Excel freezes or crashes during a VBA refresh, it is often due to a memory conflict with very large datasets. Try clearing the cache in the Power Query options or breaking the refresh into smaller, separate queries rather than one massive "RefreshAll" command. Additionally, ensure that no other cells in the workbook are being edited (cell edit mode) when the macro runs, as VBA cannot execute while a user is typing inside a cell.
Frequently Asked Questions
Can I refresh Power Query on a Mac?
While Power Query is available on Mac, VBA support is limited and behaves differently. Most basic refresh commands work, but you may encounter issues with specific connection properties that are only available in the Windows version of Excel.
Does RefreshAll update Pivot Tables too?
Yes, ActiveWorkbook.RefreshAll updates all external data ranges, Power Queries, and Pivot Tables that are linked to those data sources. It is the most comprehensive way to ensure all dependent reports are current.
How do I stop the screen from flickering during refresh?
You can add Application.ScreenUpdating = False at the beginning of your macro and Application.ScreenUpdating = True at the end. This prevents Excel from redrawing the screen every time a table updates, making the process look smoother and often speeding it up slightly.
Can I trigger a refresh based on a cell value?
Yes, you can use the Worksheet_Change event. By writing code in the specific sheet module, you can tell Excel to run the refresh macro whenever a specific cell (like a date or a project ID) is modified by the user.
Will this work if the data source is a password-protected file?
VBA cannot easily provide the password for a Power Query connection prompt. If the data source requires a password, you must ensure the credentials are saved in the Global Permissions (Data Source Settings) so that the query can authenticate automatically without user intervention.