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.
As an alternative method for refreshing all PivotTables in the workbook, you can use ThisWorkbook.RefreshAll. This refreshes all the PivotTables in the workbook.
However, it also refreshes all query tables. So if you have data tables that are connected to an external source or the web, these will be affected by the RefreshAll method. If this is not a concern, you can simply enter ThisWorkbook.RefreshAll
into a standard module.
How to Use This Macro
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:
- Activate the Visual Basic Editor by pressing ALT + F11.
- Right-click the project/workbook name in the Project Window.
- Choose Insert -> Module.
- 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.
- Click Run button on the Visual Basic Editor toolbar.
- For more information, learn this course: Programming with Excel VBA