VBA course · Lesson 26 of 33
Pivot tables with VBA: create, filter and refresh
Build pivot tables from VBA with PivotCaches.Create, add row, column, value and filter fields, hide items, refresh, change the source and read values.
Pivot tables are Excel's fastest way to summarise a big list: drag Region to Rows, Product to Columns and Revenue to Values, and thousands of rows collapse into a small, readable report. Building one by hand is quick. But if you build the same pivot report every week, for several files or for every manager, or you want a button that refreshes and filters everything in one go, VBA is the answer.
This lesson explains the objects behind a pivot table, builds a complete report from code, adds filters, hides items, refreshes, switches the pivot to new source data and reads results back into VBA. You should know how to find the extent of your data (Find the last row and build dynamic ranges in VBA) and ideally how tables work (Excel tables in VBA: working with ListObjects), because a table is the best source for a pivot.
The source is a sales list on a sheet named SalesData, formatted as a table named tblSales:
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Date | Region | Rep | Product | Units | Revenue |
| 2 | 03-Nov-2026 | North | Ana | Laptop | 3 | 2700 |
| 3 | 05-Nov-2026 | South | Ben | Monitor | 5 | 1250 |
| 4 | 08-Nov-2026 | North | Ana | Monitor | 2 | 500 |
| 5 | 12-Nov-2026 | East | Chloe | Laptop | 4 | 3600 |
| 6 | 17-Nov-2026 | South | Ben | Laptop | 2 | 1800 |
| 7 | 21-Nov-2026 | East | Chloe | Accessories | 10 | 350 |
| 8 | 26-Nov-2026 | North | Dev | Accessories | 6 | 210 |
SalesData sheet: table tblSales in A1:F8
The objects: PivotCache, PivotTable, PivotField, PivotItem
Every pivot table is built in two layers:
- A PivotCache is a hidden copy of the source data stored inside the workbook. The pivot table calculates from the cache, not from the sheet. That is why a pivot does not change until you refresh it: refreshing reloads the cache from the source.
- A PivotTable is the visible report built on a cache. Several pivot tables can share one cache, which saves memory.
- Each column of the source becomes a PivotField (
Region,Product,Revenue...). You place a field in an area by setting its Orientation. - Each distinct value inside a field is a PivotItem (
North,South,East). Items can be shown or hidden.
| Orientation constant | Area in the field list |
|---|---|
| xlRowField | Rows |
| xlColumnField | Columns |
| xlPageField | Filters (the report filter above the pivot) |
| xlDataField | Values (usually added with AddDataField) |
| xlHidden | Removed from the pivot |
Creating a pivot table
Option Explicit
Sub CreateSalesPivot()
Dim wb As Workbook
Dim wsPivot As Worksheet
Dim pc As PivotCache
Dim pt As PivotTable
Set wb = ThisWorkbook
' A fresh sheet for the report; delete an old one silently if it exists
Application.DisplayAlerts = False
On Error Resume Next
wb.Worksheets("Revenue pivot").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Set wsPivot = wb.Worksheets.Add(After:=wb.Worksheets("SalesData"))
wsPivot.Name = "Revenue pivot"
' 1. The cache: source is the table name, so it grows with the data
Set pc = wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="tblSales", Version:=xlPivotTableVersion15)
' 2. The pivot table, top-left corner in A3
Set pt = pc.CreatePivotTable(TableDestination:=wsPivot.Range("A3"), _
TableName:="ptRevenue", DefaultVersion:=xlPivotTableVersion15)
' 3. Fields
pt.ManualUpdate = True ' do not recalculate after each step
With pt.PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
With pt.PivotFields("Product")
.Orientation = xlColumnField
.Position = 1
End With
With pt.AddDataField(pt.PivotFields("Revenue"), "Total revenue", xlSum)
.NumberFormat = "#,##0"
End With
pt.ManualUpdate = False ' now calculate once
pt.TableStyle2 = "PivotStyleMedium9"
End SubStep by step:
PivotCaches.Createmakes the cache.SourceType:=xlDatabasemeans "a range or table in Excel". Passing the table name"tblSales"asSourceDatais the best choice, because the cache then follows the table when rows are added. A range address such as"SalesData!R1C1:R8C6"also works but is fixed in size.CreatePivotTableputs the report on the sheet.TableNameis the name you use later to find it again.- Setting
Orientationmoves a field into an area.AddDataFieldplaces a field in Values with a caption and a summary function, and returns the data field, so you can format it straight away withWith.
ManualUpdate = True stops the pivot from recalculating after every single field change, which is noticeably faster on large data. Remember to set it back to False, or the pivot will not show its final state.
The result, starting in A3 (row 3 shows the "Total revenue" caption and "Column Labels"):
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 4 | Row Labels | Accessories | Laptop | Monitor | Grand Total |
| 5 | East | 350 | 3,600 | 3,950 | |
| 6 | North | 210 | 2,700 | 500 | 3,410 |
| 7 | South | 1,800 | 1,250 | 3,050 | |
| 8 | Grand Total | 560 | 8,100 | 1,750 | 10,410 |
ptRevenue with the default compact layout (number format #,##0)
About the Version argument
xlPivotTableVersion15 (the value 6) creates a pivot table in the format of Excel 2013 and later, which supports every modern feature. If you leave Version out, Excel uses an older default (Excel 2007 format), and some features such as the data model or newer filters are not available. If the workbook must also open in Excel 2010, use xlPivotTableVersion14. On a Mac, Excel 2016 and later understand the same constants.
Summary functions and number formats
The third argument of AddDataField is the summary function. The common ones are xlSum, xlCount, xlAverage, xlMax and xlMin. You can add the same source field twice with different functions, and show a value as a percentage of a total:
Sub AddMoreValues()
Dim pt As PivotTable
Set pt = ThisWorkbook.Worksheets("Revenue pivot").PivotTables("ptRevenue")
pt.ManualUpdate = True
' Remove Product from columns so the values sit side by side
pt.PivotFields("Product").Orientation = xlHidden
With pt.AddDataField(pt.PivotFields("Revenue"), "Average sale", xlAverage)
.NumberFormat = "#,##0.00"
End With
With pt.AddDataField(pt.PivotFields("Revenue"), "Share of revenue", xlSum)
.Calculation = xlPercentOfColumn
.NumberFormat = "0.0%"
End With
pt.ManualUpdate = False
End SubThe caption of a data field must differ from the source field's name: "Revenue" would clash with the field Revenue, which is why the captions here are "Total revenue", "Average sale" and "Share of revenue". With the sample data North gets 3,410 of 10,410, which shows as 32.8%.
Report filters and hiding items
A page field (the Filters area) filters the whole report by one value:
Sub FilterByRep()
Dim pt As PivotTable
Dim pf As PivotField
Set pt = ThisWorkbook.Worksheets("Revenue pivot").PivotTables("ptRevenue")
Set pf = pt.PivotFields("Rep")
pf.Orientation = xlPageField
pf.Position = 1
pf.ClearAllFilters
pf.CurrentPage = "Ana"
MsgBox "Showing Ana only. Click OK to show everyone."
pf.ClearAllFilters ' back to (All)
End SubCurrentPage must be a value that exists in the field, spelled exactly as in the data, otherwise you get run-time error 1004. Calling ClearAllFilters first resets any earlier selection.
To show several values but not all, set the Visible property of individual PivotItems:
Sub HideAccessories()
Dim pt As PivotTable
Dim pi As PivotItem
Set pt = ThisWorkbook.Worksheets("Revenue pivot").PivotTables("ptRevenue")
With pt.PivotFields("Product")
.ClearAllFilters
For Each pi In .PivotItems
pi.Visible = (pi.Name <> "Accessories")
Next pi
End With
End Subpi.Visible = (pi.Name <> "Accessories") sets Visible to True for every item except Accessories. Two traps here: at least one item must stay visible, or Excel raises an error; and looping through thousands of items is slow, so turn on ManualUpdate for big fields.
Refreshing
When the source data changes, the pivot does not notice until it is refreshed. There are three levels:
Sub RefreshExamples()
Dim pt As PivotTable
Set pt = ThisWorkbook.Worksheets("Revenue pivot").PivotTables("ptRevenue")
pt.RefreshTable ' refresh this pivot (reloads its cache)
pt.PivotCache.Refresh ' refresh the cache and every pivot that shares it
ThisWorkbook.RefreshAll ' every pivot, query and connection in the workbook
End SubRefreshAll is the simplest choice for a "Refresh report" button. Be aware that it also refreshes Power Query queries and external connections, which may be slow or ask for a password.
To refresh automatically whenever the file is opened, either set pc.RefreshOnFileOpen = True once (Excel remembers it), or use the Workbook_Open event in the ThisWorkbook module (Events: macros that run by themselves):
Private Sub Workbook_Open()
Dim ws As Worksheet
Dim pt As PivotTable
For Each ws In Me.Worksheets
For Each pt In ws.PivotTables
pt.PivotCache.Refresh
Next pt
Next ws
End SubPointing a pivot at new data: ChangePivotCache
If the pivot was built on a fixed range and the data has grown, or you want to point an existing report at another sheet, create a new cache and switch the pivot over. All the fields and formatting stay in place, as long as the new source has the same column headings.
Sub SwitchToDecember()
Dim pt As PivotTable
Dim src As Range
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("SalesDec")
Set src = ws.Range("A1").CurrentRegion
Set pt = ThisWorkbook.Worksheets("Revenue pivot").PivotTables("ptRevenue")
pt.ChangePivotCache ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=src.Address(ReferenceStyle:=xlR1C1, External:=True), _
Version:=xlPivotTableVersion15)
pt.RefreshTable
End SubAddress(External:=True) includes the workbook and sheet name, such as [Sales.xlsm]SalesDec!R1C1:R230C6, so the cache knows exactly where to look. R1C1 style is the form PivotCaches.Create handles most reliably across versions and languages.
Reading values with GetPivotData
Once a pivot exists, VBA can read any number from it by naming the data field and the items, just like the GETPIVOTDATA worksheet function. This is far safer than reading a fixed cell address, because pivot layouts move when items are added.
Sub ReadNorthRevenue()
Dim pt As PivotTable
Dim cell As Range
Set pt = ThisWorkbook.Worksheets("Revenue pivot").PivotTables("ptRevenue")
On Error Resume Next
Set cell = pt.GetPivotData("Total revenue", "Region", "North")
On Error GoTo 0
If cell Is Nothing Then
MsgBox "North is not in the pivot (filtered out or no data)."
Else
MsgBox "North revenue: " & Format(cell.Value, "#,##0") ' 3,410
End If
End SubGetPivotData returns the cell that holds the value, so .Value gives the number and .Address would tell you where it is. Pairs of field and item narrow the result: pt.GetPivotData("Total revenue", "Region", "North", "Product", "Laptop") returns 2,700. If the combination is not visible, the method raises an error; the short On Error Resume Next block catches that and leaves cell as Nothing (Error handling and debugging in VBA).
Layout options
A few properties make the report look like a normal table, which is handy when the pivot feeds other formulas or is copied into an email:
Sub TidyLayout()
Dim pt As PivotTable
Dim pf As PivotField
Set pt = ThisWorkbook.Worksheets("Revenue pivot").PivotTables("ptRevenue")
pt.RowAxisLayout xlTabularRow
pt.RepeatAllLabels xlRepeatLabels
pt.ColumnGrand = True
pt.RowGrand = True
For Each pf In pt.RowFields
pf.Subtotals(1) = False ' turn off the Automatic subtotal
Next pf
End SubIn tabular layout the "Row Labels" heading becomes the real field name, "Region".
Common mistakes
- Forgetting to refresh after the source changes, and wondering why the totals are old.
- Building the cache on a fixed address so new rows are left out. Use a table name.
- A data field caption equal to the field name ("Revenue"), which raises error 1004.
- Hiding every item of a field, which is not allowed.
- Reading pivot results from fixed cells like
Range("C6")instead ofGetPivotData. - Creating a new pivot on a sheet where one already exists in the same place: pivots cannot overlap.
- Leaving
ManualUpdate = Trueafter an error, so the pivot looks frozen. Set it back in your error handler.
Check yourself
1. Why does a pivot table not update when you change the source data?
The cache is a stored copy; RefreshTable or PivotCache.Refresh reloads it.
2. Which line puts the Region field in the Rows area?
Orientation decides which area a field sits in.
3. Why is "tblSales" a good SourceData for PivotCaches.Create?
A table name always refers to the current size of the table; a fixed address does not.
4. What does pt.GetPivotData("Total revenue", "Region", "North") return?
It returns a Range; read .Value for the number.
5. What does ThisWorkbook.RefreshAll refresh?
RefreshAll covers every refreshable object, which can include slow external connections.