Skip to main content

Excel Macro: Refresh All PivotTables Workbook

It is common to have multiple PivotTables in the same workbook. Many times these PivotTables are linked to changing data and need to be refreshed. if you find that you need to refresh your PivotTables a lot, you can use this macro to refresh all PivotTables on demand.

Refresh All PivotTables Workbook

'------------------ Modules ------------------
Sub RefreshAllPivotTables()
'Step 1: Declare your Variables
    Dim ws As Worksheet
    Dim pt As PivotTable
'Step 2: Loop through each sheet in workbook
    For Each ws In ThisWorkbook.Worksheets
'Step 3: Loop through each PivotTable
        For Each pt In ws.PivotTables
            pt.RefreshTable
        Next pt
    Next ws
End Sub

How This Macro Works

This macro first loops through the worksheets and then loops through the PivotTables. In each loop, the macro refreshes the PivotTable.

1. Step 1 first declares an object called ws, which holds each worksheet we loop through. It also declares an object called pt, which holds each PivotTable the macro loops through.

2. Step 2 starts the looping, telling Excel we want to evaluate all worksheets in this workbook. Notice we are using ThisWorkbook instead of ActiveWorkbook. The ThisWorkbook object refers to the workbook that the code is contained in. The ActiveWorkbook object refers to the workbook that is currently active. They often return the same object, but if the workbook running the code is not the active workbook, they return different objects. In this case, we don’t want to risk refreshing PivotTables in other workbooks, so we use ThisWorkbook.

3. Step 3 loops through all the PivotTables in each worksheet, and then triggers the RefreshTable method. After all PivotTables have been refreshed, the macro moves to the next sheet. After all sheets have been evaluated, the macro ends.

Most VBA code should be placed in Standard Modules unless specified.

If you see a comment '------------------ Modules------------------ in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?

The following steps teach you how to put VBA code into a Standard Module:

  1. Activate the Visual Basic Editor by pressing ALT + F11.
  2. Right-click the project/workbook name in the Project Window.
  3. Choose Insert -> Module.
  4. Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
  5. Click Run button on the Visual Basic Editor toolbar.
  6. For more information, learn this course: Programming with Excel VBA

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>