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.

Advanced 22 min read

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:

ABCDEF
1DateRegionRepProductUnitsRevenue
203-Nov-2026NorthAnaLaptop32700
305-Nov-2026SouthBenMonitor51250
408-Nov-2026NorthAnaMonitor2500
512-Nov-2026EastChloeLaptop43600
617-Nov-2026SouthBenLaptop21800
721-Nov-2026EastChloeAccessories10350
826-Nov-2026NorthDevAccessories6210

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 constantArea in the field list
xlRowFieldRows
xlColumnFieldColumns
xlPageFieldFilters (the report filter above the pivot)
xlDataFieldValues (usually added with AddDataField)
xlHiddenRemoved from the pivot

Creating a pivot table

VBA
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 Sub
Build a revenue report: regions down, products across

Step by step:

  1. PivotCaches.Create makes the cache. SourceType:=xlDatabase means "a range or table in Excel". Passing the table name "tblSales" as SourceData is 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.
  2. CreatePivotTable puts the report on the sheet. TableName is the name you use later to find it again.
  3. Setting Orientation moves a field into an area. AddDataField places a field in Values with a caption and a summary function, and returns the data field, so you can format it straight away with With.

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"):

ABCDE
4Row LabelsAccessoriesLaptopMonitorGrand Total
5East3503,6003,950
6North2102,7005003,410
7South1,8001,2503,050
8Grand Total5608,1001,75010,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:

VBA
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 Sub
Add an average price per sale and each region's share of revenue

The 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:

VBA
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 Sub
Filter the whole report to one rep, then back to all

CurrentPage 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:

VBA
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 Sub
Hide the Accessories column, keep everything else

pi.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:

VBA
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 Sub
Three ways to refresh

RefreshAll 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):

VBA
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 Sub
In the ThisWorkbook module: refresh every pivot table when the file opens

Pointing 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.

VBA
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 Sub
Point ptRevenue at the December data on another sheet

Address(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.

VBA
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 Sub
Read North's total revenue from the pivot

GetPivotData 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:

VBA
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 Sub
Tabular layout with repeated labels and no subtotals

In 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 of GetPivotData.
  • Creating a new pivot on a sheet where one already exists in the same place: pivots cannot overlap.
  • Leaving ManualUpdate = True after 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?

2. Which line puts the Region field in the Rows area?

3. Why is "tblSales" a good SourceData for PivotCaches.Create?

4. What does pt.GetPivotData("Total revenue", "Region", "North") return?

5. What does ThisWorkbook.RefreshAll refresh?