To force Excel VBA to refresh all external data connections and wait until every refresh completes before proceeding, you must disable background querying and use proper error handling. This prevents the macro from moving to the next line while data is still loading, which avoids errors like #N/A or stale results. No add-ins or extra tools are required—just standard VBA with Excel’s built-in connection settings.

What You'll Need

  • Excel with Developer tab enabled (to access the VBA editor)
  • Workbooks containing external data connections (e.g., Power Query, PivotTables linked to external sources, or legacy Data Connections)
  • Basic familiarity with writing or editing VBA macros

Step-by-Step

  1. Open your Excel workbook and press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
  2. In the VBA editor, go to Insert > Module to create a new standard module if one doesn’t already exist.
  3. Enter the following VBA code into the module window:
    Sub RefreshAllAndWait()
        Dim conn As WorkbookConnection
        Dim odbcConn As ODBCCConnection
        Dim olapConn As OLAPConnection
        Dim ws As Worksheet
        Dim pt As PivotTable
        
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        
        ' Disable background refresh for all connections
        For Each conn In ThisWorkbook.Connections
            On Error Resume Next
            If conn.Type = xlConnectionTypeODBC Then
                Set odbcConn = conn.ODBCConnection
                If Not odbcConn Is Nothing Then odbcConn.BackgroundRefresh = False
            ElseIf conn.Type = xlConnectionTypeOLEDB Then
                conn.OLEDBConnection.BackgroundRefresh = False
            ElseIf conn.Type = xlConnectionTypeWEB Then
                conn.WebConnection.BackgroundRefresh = False
            ElseIf conn.Type = xlConnectionTypePOWERQUERY Then
                conn.ModelConnection.BackgroundRefresh = False
            End If
            On Error GoTo 0
        Next conn
        
        ' Disable background refresh for all PivotTables
        For Each ws In ThisWorkbook.Worksheets
            For Each pt In ws.PivotTables
                pt.PivotCache.BackgroundRefresh = False
            Next pt
        Next ws
        
        ' Refresh all connections and wait
        ThisWorkbook.RefreshAll
        
        ' Force calculation to ensure all formulas update
        DoEvents
        Application.CalculateUntilAsyncDone
        
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
        
        MsgBox "All data has been refreshed and calculations completed.", vbInformation
    End Sub
  4. Save the workbook as a macro-enabled file (.xlsm) by going to File > Save As > Excel Macro-Enabled Workbook.
  5. Close the VBA editor and return to Excel. Press Alt + F8, select RefreshAllAndWait, and click Run.
  6. Verify the macro completes only after all connections finish loading—check pivot tables, Power Query queries, and external linked data for current values. If successful, a confirmation message box appears.

Common Mistakes

  • Using ThisWorkbook.RefreshAll alone without disabling background refresh—this causes the macro to continue before data loads, leading to inconsistent results.
  • Skipping Application.CalculateUntilAsyncDone, which leaves asynchronous formulas (e.g., those dependent on Power Query) uncalculated when the next line runs.
  • Forgetting to set ScreenUpdating = False and Calculation = Manual, which slows execution and may cause screen flicker or partial updates.
  • Assuming all connection types support BackgroundRefresh—some Power Pivot or complex models require explicit property checks to avoid runtime errors.
  • Not error-handling the connection object assignments, which can crash the macro on unsupported or corrupted connections.

Tips

  • Run the macro during off-peak hours if refreshing large datasets—external queries can take minutes depending on network speed and source size.
  • For Power Query–only workbooks, consider using Application.CalculateUntilAsyncDone after ActiveWorkbook.Queries.Load if you load queries manually via VBA.
  • Wrap the code in a On Error GoTo ErrHandler block if sharing it widely; log errors to a hidden sheet for debugging.
  • Test with a small dataset first to confirm wait behavior: add a timestamp before and after RefreshAll to verify timing.
  • Use ThisWorkbook.Connections.Count in the Immediate Window (Ctrl+G in VBA) to verify how many connections exist before running.
  • If pivot tables hang, manually check Data > Connections in Excel and ensure each pivot’s Properties > Usage > Background Refresh is unchecked.

Troubleshooting

If the macro still proceeds before data completes:

  1. Confirm background refresh is disabled: In Excel, go to Data > Connections, double-click each connection, and verify Enable background refresh is unchecked. Re-run the macro after fixing manually.
  2. Check for Power Pivot model delays: If using Power Pivot, ensure Application.CalculateUntilAsyncDone is present. If the macro still finishes early, add a short loop with DoEvents and a timeout counter (e.g., max 30 seconds) to poll Application.BackgroundQuery status.
  3. Validate connection types: Run a diagnostic macro that lists all connection types (Debug.Print conn.Name, conn.Type) and ensure your code handles each one. Missing a type like xlConnectionTypeWORKSHEET won’t affect refresh but indicates a mismatch.
  4. Disable add-ins: Some third-party add-ins interfere with refresh timing. Restart Excel in safe mode (hold Ctrl while clicking Excel) and test the macro there.
  5. Check data source status: If the external source is offline (e.g., SharePoint or database server down), refresh will time out. Manually refresh one query in Excel to confirm it works outside VBA.
If errors occur during macro execution:
  1. Use断点: Place a breakpoint on the line after RefreshAll and step through (F8) to see where it stalls or fails.
  2. Check references: In the VBA editor, go to Tools > References and ensure no items show as MISSING.
  3. Reset calculation mode: Manually set Formulas > Calculation Options > Automatic before running the macro again.
  4. Repair workbook: Copy all sheets and modules into a new workbook and try the macro there—corrupted files sometimes break connection references.

Frequently Asked Questions

Does this work for Excel Online or Microsoft 365 web version?

No—VBA macros do not run in Excel Online. This method only works in desktop Excel for Windows or Mac.

Why does my macro still show old data even after refresh?

Excel may cache query results. Ensure Data > Queries & Connections has Enable background refresh disabled for each query, and that your code sets BackgroundRefresh = False as shown.

Can I refresh only specific connections instead of all?

Yes—modify the loop to target connections by name: If conn.Name = "MyQuery" Then conn.OLEDBConnection.BackgroundRefresh = False, then use conn.Refresh instead of ThisWorkbook.RefreshAll.

How long should I expect the wait to take?

It depends on your data size and source. Small Power BI datasets may refresh in seconds; large SQL queries over slow networks can take minutes. The macro waits exactly as long as needed—no fixed timeout.

Will this work with linked tables from CSV or text files?

Yes, but only if the connection is defined via Data > Get Data (Power Query) or legacy From Text/CSV. Legacy links (e.g., Data > From Other Sources > From Microsoft Query) also respect BackgroundRefresh = False when explicitly set.

What happens if a connection fails during refresh?

The macro pauses and displays an error unless you add error handling. To allow the macro to continue, wrap conn.Refresh calls in On Error Resume Next and log failures to a hidden sheet or message box.