Mearns Learns

Table Mountain built with blocks

Refresh Power Query

Queries can be refreshed in a few different ways.

  1. Right click on the query table and select Refresh.
  2. On the *Data menu tab, click on the Refresh All icon.
  3. On the Queries & Connections pane, right click on the query and select Refresh.
  4. By using VBA code

IMPORTANT: One thing to be aware of, if you have pivot tables using the query table as a source, you will need to refresh twice. Once to update the query and once to update the pivot table.

Using VBA code

Here are various code options:

The easy way is to refresh everything.

Sub Refresh_Everything()

    ThisWorkbook.RefreshAll
    ThisWorkbook.RefreshAll
'This will run a refresh for everything.
'But it needs to be run twice so that the Pivots refresh with the new data
'And the assumption is that background refresh is disabled...

End Sub

This code updates all the connections and pivot tables separately

Sub Refresh_All_Data_Connections()

Dim objConnection As Object
Dim bBackground As Boolean
Dim PT As PivotTable
Dim WS As Worksheet

    For Each objConnection In ThisWorkbook.Connections

        bBackground = objConnection.OLEDBConnection.BackgroundQuery
'Get the current background-refresh value

        objConnection.OLEDBConnection.BackgroundQuery = False
'Temporarily disable background-refresh

        objConnection.Refresh
'Use this to refresh all queries

        objConnection.OLEDBConnection.BackgroundQuery = bBackground
'Set background-refresh value back to original value

    Next

    For Each WS In ThisWorkbook.Worksheets
        For Each PT In WS.PivotTables
          PT.RefreshTable
        Next PT
    Next WS
'Use this to refresh all pivots in the workbook.
'Depending on the workbook structure, a pivot may be refreshed multiple times,
' if the same cache has been reused.

End Sub

This code will update a single connection and a single pivot cache.

Sub Refresh_Single_Data_Connection()

Dim objConnection As Object
Dim bBackground As Boolean
Dim PT As PivotTable
Dim WS As Worksheet

    For Each objConnection In ThisWorkbook.Connections

        bBackground = objConnection.OLEDBConnection.BackgroundQuery
'Get the current background-refresh value

        objConnection.OLEDBConnection.BackgroundQuery = False
'Temporarily disable background-refresh

        If objConnection.Name = "Query - Import" Then
            objConnection.Refresh
        End If
'Use this to refresh a single query
'Prefix the Query name with "Query -"

        objConnection.OLEDBConnection.BackgroundQuery = bBackground
'Set background-refresh value back to original value

    Next

    Sheets("Sheet1").PivotTables("PivotTable1").RefreshTable
'Refresh a single pivot cache and all pivots using it.

End Sub