Tabellab

How Excel Sees a PivotTable

Lesson 1 of 7Reading

Three objects, not one

When you build a PivotTable by hand it feels like a single thing. In code it is three, and knowing which is which removes most of the confusion:

  • PivotCache โ€” an invisible copy of the source data, held in memory inside the workbook. This is what makes a pivot fast, and why the report does not change when you edit the source until you refresh.
  • PivotTable โ€” the visible report on the sheet. It reads from a cache and knows nothing about the original range.
  • PivotField โ€” one column of the source, placed in the rows, columns, values or filter area.

Caches belong to the workbook, PivotTables to a worksheet, fields to a PivotTable. Several PivotTables can share one cache, which keeps the file small and lets one refresh update them all โ€” and causes the side effect people find baffling: group a date field in one pivot and the grouping appears in the other, because grouping is stored in the cache, not in the report.

First, something to look at

Run this once. It creates a small source table and one PivotTable, so the audit macro below has something to report on. Its lines are unpacked properly in lessons 2 to 4.

Option Explicit

Sub MakePivotDemo()
    Dim wb As Workbook
    Dim wsData As Worksheet
    Dim wsRep As Worksheet
    Dim pc As PivotCache
    Dim pt As PivotTable
    Dim tag As String
    Dim r As Long

    Set wb = ThisWorkbook
    tag = Format(Now, "hhmmss")

    Set wsData = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
    wsData.Name = "Demo Data " & tag
    wsData.Range("A1:C1").Value = Array("Region", "Product", "Amount")

    For r = 2 To 25
        wsData.Cells(r, 1).Value = Choose((r Mod 3) + 1, "North", "South", "West")
        wsData.Cells(r, 2).Value = Choose((r Mod 2) + 1, "Cable", "Adapter")
        wsData.Cells(r, 3).Value = 100 + r * 7
    Next r

    Set wsRep = wb.Worksheets.Add(After:=wsData)
    wsRep.Name = "Demo Report " & tag

    Set pc = wb.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=wsData.Range("A1").CurrentRegion)

    Set pt = pc.CreatePivotTable( _
        TableDestination:=wsRep.Range("A3"), _
        TableName:="ptDemo" & tag)

    pt.PivotFields("Region").Orientation = xlRowField
    pt.PivotFields("Product").Orientation = xlColumnField
    pt.AddDataField pt.PivotFields("Amount"), "Total", xlSum
End Sub

The macro: an inventory of every pivot in the workbook

This is the one worth keeping. Hand it a workbook full of pivots somebody else built and it writes out, on one sheet, where each report lives, which cache it reads, how many records that cache holds, when it was last refreshed and where every field sits.

Sub AuditPivotTables()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim wsOut As Worksheet
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim placement As String
    Dim nextRow As Long

    Set wb = ThisWorkbook

    On Error Resume Next
    Set wsOut = wb.Worksheets("Pivot Audit")
    On Error GoTo 0

    If wsOut Is Nothing Then
        Set wsOut = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
        wsOut.Name = "Pivot Audit"
    End If

    wsOut.Cells.Clear
    wsOut.Range("A1:G1").Value = Array("Sheet", "PivotTable", "Cache", _
        "Records in cache", "Last refresh", "Field", "Sits in")
    wsOut.Range("A1:G1").Font.Bold = True
    nextRow = 2

    For Each ws In wb.Worksheets
        For Each pt In ws.PivotTables
            For Each pf In pt.PivotFields
                Select Case pf.Orientation
                    Case xlRowField
                        placement = "Rows"
                    Case xlColumnField
                        placement = "Columns"
                    Case xlDataField
                        placement = "Values"
                    Case xlPageField
                        placement = "Filter"
                    Case Else
                        placement = "not used"
                End Select

                wsOut.Cells(nextRow, 1).Value = ws.Name
                wsOut.Cells(nextRow, 2).Value = pt.Name
                wsOut.Cells(nextRow, 3).Value = pt.CacheIndex
                wsOut.Cells(nextRow, 4).Value = pt.PivotCache.RecordCount
                wsOut.Cells(nextRow, 5).Value = pt.RefreshDate
                wsOut.Cells(nextRow, 6).Value = "[" & pf.SourceName & "]"
                wsOut.Cells(nextRow, 7).Value = placement
                nextRow = nextRow + 1
            Next pf
        Next pt
    Next ws

    If nextRow = 2 Then
        wsOut.Range("A2").Value = "No PivotTables in this workbook."
    End If

    wsOut.Columns("E").NumberFormat = "yyyy-mm-dd hh:mm"
    wsOut.Columns("A:G").AutoFit
    wsOut.Activate
End Sub

Line by line

  • The three nested For Each loops are the object model itself: worksheets hold PivotTables, PivotTables hold PivotFields. Only the caches sit elsewhere, on the workbook.
  • pt.CacheIndex is the number of the cache this report reads. Two pivots showing the same number share one cache โ€” they refresh together and share any grouping.
  • pt.PivotCache.RecordCount is how many rows the snapshot holds. Fewer records than the source has rows is the classic sign of a pivot built over a range that has since grown.
  • pt.RefreshDate is when that snapshot was taken. A pivot never hides that it is stale; nobody ever looks.
  • pf.Orientation says where a field sits. Unused fields report xlHidden, hence the "not used" rows โ€” a column exists in the cache whether the report shows it or not.
  • pf.SourceName is the column name in the source, pf.Name the caption in the report. For a value field the two differ: Amount against Sum of Amount.
  • The square brackets are deliberate: they make a trailing space visible, which is the point of the next section.
  • If nextRow never moved, the workbook has no pivots and the macro says so.

The trap: "Unable to get the PivotFields property"

Run-time error 1004 on a line like pt.PivotFields("Amount").Orientation = xlDataField hardly ever means the field is missing. It means the name is not exactly Amount. Two everyday causes: the header cell in the source ends in a space nobody can see; or the field is already in the values area, where its name has become Sum of Amount while SourceName stays Amount. On screen the two cases look identical.

' Ask the pivot what it actually has, instead of guessing
Dim pt As PivotTable
Dim pf As PivotField

Set pt = ActiveSheet.PivotTables(1)

For Each pf In pt.PivotFields
    Debug.Print "[" & pf.SourceName & "] is shown as [" & pf.Name & "]"
Next pf

Cure it at the source: trim the header row before building the cache, and reach value fields through pt.DataFields. The audit macro is the same idea at workbook scale โ€” when a pivot script fails on a file you did not write, run the audit first and read the real names off the sheet.

A pivot needs a flat list as its source: one header row, no blank headers, no merged cells, no empty rows through the middle, one record per row. A table with a column per month across the top is a report, not source data.

How this course goes on

This lesson only reads pivots; the next three build one. Lesson 2 creates the cache and shows why a Table beats a fixed range as its source, lesson 3 turns a cache into a report on a sheet, lesson 4 places fields into the rows, columns and values areas. After that come summary functions and number formats, filters and slicers, and the rebuild patterns that stop a monthly report breaking the month the data grows.

Who this lesson is for, and why pivots belong in code

If you build the same PivotTable every month, you already know the routine: paste the new export, check the source range, drag Region into Rows and Product into Columns, drop Amount into Values, change Count to Sum, fix the number format, rename the sheet. Ten minutes on a good day, and a wrong total on a bad one because the range stopped at last month's last row. This course is for analysts, controllers and anyone else who owns a recurring pivot report and has written or recorded at least a simple macro.

By the end of the course a macro builds, fills, filters and refreshes the whole report in one click. This free first lesson does something more modest and more important: it shows how Excel sees a PivotTable from VBA. Once you know the three objects behind every pivot, the code in the later lessons reads naturally, and error messages such as "Unable to get the PivotFields property" stop being mysterious.

The core idea: three objects, not one

On screen a PivotTable looks like one thing. In the object model it is three, and each lives in a different place.

  • PivotCache belongs to the workbook. It is a snapshot of the source data, stored inside the file. The report never reads your cells directly, it reads this snapshot. That is why editing the source changes nothing until you refresh, and why a pivot keeps showing its numbers even after the source sheet has been deleted.
  • PivotTable belongs to a worksheet. It is the visible report: the layout, the totals, the formatting. It knows which cache it reads, through pt.PivotCache and pt.CacheIndex, and nothing else about the source.
  • PivotField belongs to a PivotTable. Each column heading of the source becomes a field, and its Orientation says where it sits: Rows, Columns, Values, Filters or nowhere.

Several PivotTables can share one cache. That keeps the file small and means one refresh updates every report built on it. It also explains a side effect that confuses people: grouping is stored in the cache, so if you group a date field by month in one pivot, every other pivot on the same cache shows months as well. When you meet that in a real workbook, compare the CacheIndex of the two reports and you have the explanation.

Cache on the workbook, reports on the sheetsWorkbookwb.PivotCachesPivotCache 1copy of A1:C2524 recordsPivotTable ptDemoCacheIndex = 1Second PivotTableCacheIndex = 1Region: RowsProduct: ColumnsAmount: ValuesOne refresh of the cache updates both reports.Grouping a date field in one report shows up in the other.
The cache lives on the workbook, the reports live on worksheets, and every field of a report has one orientation. Two reports with the same CacheIndex refresh together.

The worked example: the demo source and its report

The lab starts with MakePivotDemo. It adds a data sheet with three columns and 24 records, then builds a report called ptDemo from it. The region and product are spread evenly with Choose and Mod, and the amount is 100 + r * 7 for row r, so every number below can be checked by hand. These are the first rows of the source, exactly as the macro writes them:

RowA: RegionB: ProductC: Amount
2WestCable114
3NorthAdapter121
4SouthCable128
5WestAdapter135
6NorthCable142
7SouthAdapter149
โ€ฆโ€ฆโ€ฆโ€ฆ
25SouthAdapter275

Row 2 gets West because 2 Mod 3 is 2 and Choose(3, "North", "South", "West") returns the third item. Row 3 gets North because 3 Mod 3 is 0. The same idea alternates Cable and Adapter. The finished pivot, with Region in Rows, Product in Columns and the sum of Amount in Values, looks like this:

TotalAdapterCableGrand Total
North7368201,556
South8487641,612
West7927081,500
Grand Total2,3762,2924,668

You can verify any cell with an ordinary formula on the data sheet. North and Adapter, for example, is =SUMIFS(C:C,A:A,"North",B:B,"Adapter"), which returns 736. The grand total is =SUM(C2:C25), 4,668. Checking a pivot against a SUMIFS once is a good habit whenever you automate a report: if the two disagree, the cache does not cover the range you think it covers.

ptDemo: Total of Amount by Region and ProductAdapterCable0300600900736820North848764South792708West
The demo report as a chart: each region holds 8 records, and the totals range from 708 (West, Cable) to 848 (South, Adapter).

The four lines that build the report

The lab explains these lines in detail in lessons 2 to 4, but it helps to see now how each one maps to an object from the diagram.

Set pc = wb.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=wsData.Range("A1").CurrentRegion)

Set pt = pc.CreatePivotTable( _
    TableDestination:=wsRep.Range("A3"), _
    TableName:="ptDemo" & tag)

pt.PivotFields("Region").Orientation = xlRowField
pt.PivotFields("Product").Orientation = xlColumnField
pt.AddDataField pt.PivotFields("Amount"), "Total", xlSum

  • wb.PivotCaches.Create is called on the workbook, because that is where caches live. xlDatabase means a range of cells, and CurrentRegion expands from A1 to the whole block of data.
  • pc.CreatePivotTable is called on the cache, not on the sheet. The cache produces the report and places it at A3, leaving room above for filters.
  • Setting Orientation moves a field into an area, exactly like dragging it in the field list.
  • AddDataField puts Amount into Values with the caption Total and the function xlSum. The caption must differ from the source name, which is why it is not called Amount.

The macro worth keeping: an inventory of every pivot

The second macro in the lab, AuditPivotTables, only reads. It walks every worksheet, every PivotTable on it and every field of each table, and writes one row per field onto a sheet called Pivot Audit. Its heart is three nested loops that follow the object model:

For Each ws In wb.Worksheets
    For Each pt In ws.PivotTables
        For Each pf In pt.PivotFields
            ' one output row per field
        Next pf
    Next pt
Next ws

For each field it records the sheet name, pt.Name, pt.CacheIndex, pt.PivotCache.RecordCount, pt.RefreshDate, the field's SourceName in square brackets and a plain-language placement read from pf.Orientation with a Select Case. Run on the demo workbook, the first rows look like this:

SheetPivotTableCacheRecords in cacheLast refreshFieldSits in
Demo Report 101530ptDemo1015301242026-10-31 10:15[Region]Rows
Demo Report 101530ptDemo1015301242026-10-31 10:15[Product]Columns

The sheet names and the time stamp are examples: the macro adds the time it ran as hhmmss, so yours will differ. The useful columns are the cache number and the record count. Run MakePivotDemo a second time and the audit shows a second report with cache 2, because each run builds its own cache from its own data sheet. In a workbook you inherited, a record count lower than the number of rows in the source is the classic sign of a pivot built over a fixed range that has since grown.

Why not simply record the macro?

The macro recorder is a fine way to discover the name of a property, and a poor way to build a report that has to work next month. Record yourself inserting a pivot and you get code with the source address typed in as text, such as "Sheet1!R1C1:R25C3", a report name like PivotTable1 that changes every time, and a Select before almost every line. Run that recording on a file with 900 rows and it still reads 24. Run it twice and the second run stops because PivotTable1 already exists.

Written code avoids all three problems by working with objects held in variables. pc is the cache, pt is the report, and neither depends on what is selected. The source is worked out at run time, the name is chosen by you, and the routine can clear and rebuild the report as often as you like. That is the style the whole course uses, and it is why the first lesson spends its time on the object model instead of the ribbon.

Reading an audit like a reviewer

The audit sheet becomes more useful the messier the workbook. Sort it by the Cache column and every group of rows with the same number is a family of reports that refresh together. Filter the Sits in column for "not used" and you see which source columns nobody looks at, which are candidates to drop from the export. Compare the Last refresh column with the date the data was pasted, and a stale report is obvious before it reaches anyone else. None of this changes a single pivot, which makes the audit safe to run on any file you receive.

Step by step: run the lesson in your own workbook

  1. Open a new workbook and save it straight away as Excel Macro-Enabled Workbook (*.xlsm) with F12, so the code is not lost.
  2. Press Alt+F11 (Mac: Opt+F11), select the workbook in the Project Explorer and choose Insert โ†’ Module.
  3. Paste both macros from the lab, MakePivotDemo and AuditPivotTables, into the module. Keep a single Option Explicit at the top.
  4. Click inside MakePivotDemo and press F5. Two new sheets appear: Demo Data and Demo Report, each with a time stamp in the name.
  5. Switch to Excel, click inside the report and open PivotTable Analyze โ†’ Change Data Source. The dialog shows the range the cache was built from. Close it with Cancel.
  6. Still on the report, look at PivotTable Analyze โ†’ PivotTable Name on the left of the ribbon. It is the name the macro gave with TableName.
  7. Press Alt+F8, choose AuditPivotTables and click Run. The Pivot Audit sheet lists every field with its placement, cache and record count.
  8. Add a row 26 to the data sheet and press Alt+F5 on the report to refresh it. Because the cache was built from the old CurrentRegion, the new row is ignored until the source is redefined. Lesson 2 shows how an Excel Table avoids this.
Open the Immediate window with Ctrl+G and type ? ActiveSheet.PivotTables(1).PivotCache.RecordCount while the report sheet is active. It is the fastest way to see how many rows a pivot really reads.

Excel PivotTables with VBA course: a PivotTable report built and refreshed by a macro
Every pivot report you build by hand can be rebuilt from code, identically, every month.

The trap: "Unable to get the PivotFields property"

Run-time error 1004 on a line such as pt.PivotFields("Amount").Orientation = xlDataField rarely means the field is missing. It means no field is called exactly Amount. Two causes cover most cases. Either the header cell in the source ends in a space nobody can see, or the field is already in the Values area, where its caption has become Sum of Amount while its SourceName is still Amount. On screen the two look the same. Ask the pivot instead of guessing:

Dim pt As PivotTable
Dim pf As PivotField

Set pt = ActiveSheet.PivotTables(1)

For Each pf In pt.PivotFields
    Debug.Print "[" & pf.SourceName & "] is shown as [" & pf.Name & "]"
Next pf

The brackets make a trailing space visible: [Amount ] stands out at once in the Immediate window. Fix it at the source by trimming the header row before you build the cache, and reach value fields through pt.DataFields, where they are listed under their captions.

Other common mistakes, and how to spot them

  • A source that is a report, not a list. A pivot needs one header row, no blank or merged headers, no empty rows in the middle and one record per row. A table with one column per month is already a summary. Symptom: fields called Jan, Feb, Mar instead of one Month field.
  • A fixed source address. Range("A1:C25") is right today and wrong next month. Symptom: RecordCount lower than the number of data rows, and totals that miss the newest records.
  • Placing the pivot at A1. Adding a filter field later needs rows above the report. Excel then asks to move the pivot, or the macro stops with an error. Start at A3.
  • Data field caption equal to the source name. AddDataField pt.PivotFields("Amount"), "Amount", xlSum raises error 1004. Use "Total", "Total amount" or "Amount " with a trailing space.
  • Unexpected shared grouping. Two pivots on the same cache share date and number grouping. Symptom: grouping changes in a report you did not touch. Check CacheIndex in the audit.
  • Relying on PivotTables(1). The index changes as soon as someone adds or deletes a pivot. Give every report a fixed name and refer to it by name, as lesson 3 shows.

Quick reference: objects, properties and shortcuts

Everything this lesson used, in one place.

ItemBelongs toWhat it gives you
wb.PivotCaches.Create(SourceType, SourceData)WorkbookA new cache from a range or Table
pc.CreatePivotTable(TableDestination, TableName)PivotCacheA new report on a sheet
ws.PivotTablesWorksheetAll reports on that sheet
pt.PivotFields("Region")PivotTableOne field by its name
pf.OrientationPivotFieldxlRowField 1, xlColumnField 2, xlPageField 3, xlDataField 4, xlHidden 0
pt.AddDataField field, caption, functionPivotTableA value field such as xlSum or xlCount
pt.CacheIndexPivotTableNumber of the cache the report reads
pt.PivotCache.RecordCountPivotCacheRows in the snapshot
pt.RefreshDatePivotTableWhen the cache was last refreshed
pf.SourceName / pf.NamePivotFieldSource column name / caption in the report
Alt+F5 / Ctrl+Alt+F5ExcelRefresh this PivotTable / refresh all
Alt+F8, F5, Ctrl+GExcel / VBA editorMacro list, run, Immediate window

Real-world uses

  • Month-end sales report. A controller pastes the new ERP export and runs one macro that rebuilds the regional pivot, applies the number format and names the sheet after the month.
  • Auditing an inherited workbook. A new analyst gets a file with a dozen pivots and runs the audit macro to see which ones share a cache, which are stale and which read a range that has grown.
  • One report per region. A sales manager needs the same pivot filtered for each of five regions. Code loops the filter and copies or exports each version, instead of five rounds of clicking.
  • Checking before a board pack goes out. A finance team compares each pivot's RecordCount with the source row count and its RefreshDate with today, and stops the pack if one is stale.

What you will build in the rest of this course

This lesson is free. Lessons 2 to 7 belong to the paid course, a one-time purchase of $9.90, and together they turn the manual monthly pivot into a single macro.

Building the PivotCache. You create caches from CurrentRegion and, better, from an Excel Table that grows by itself, set the cache options that stop deleted items lingering in filter lists, and reuse an existing cache for a second report.

Creating the PivotTable in Code. You write a routine that can run twice without failing: it creates or clears the report sheet, gives the pivot a stable name and chooses the tabular layout most reports need.

Adding Row, Column and Data Fields. You place several fields in a defined nesting order with Position, add data fields with AddDataField, avoid the caption error, and build large pivots quickly with ManualUpdate.

Changing the Summary Function and Number Format. You switch between Sum, Count and Average, show the same field twice with different summaries, display percentages of the total and format the field instead of the cells, so formatting survives every refresh.

Filtering a PivotTable. You set report filters safely, show and hide individual items, add label and value filters with PivotFilters.Add2, and create a slicer in a single line of code.

Refreshing, Rebuilding and Deleting. You learn the three levels of refresh, why refresh does not pick up new rows from a fixed range, how to delete a pivot completely with TableRange2, and a rebuild pattern that keeps a monthly report working when the data grows.

Summary

Behind every PivotTable are three objects: the cache on the workbook, the report on a worksheet and the fields inside the report. The cache is a snapshot, so the report only changes when it is refreshed, and reports that share a cache refresh and group together. When code cannot find a field, it is almost always a name that differs from what you expect, and the quickest way to find out is to ask the pivot for its SourceName and Name.

Now go back to the lab above, run MakePivotDemo twice and then AuditPivotTables. Before you look at the audit sheet, predict how many cache numbers it will show and how many records each one holds.

Frequently asked questions

What is a PivotCache in Excel VBA?

A PivotCache is a snapshot of the source data stored in the workbook. PivotTables read from the cache, not from the cells, so changes to the source only appear after a refresh.

How do I create a PivotTable with VBA?

Create a cache with wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=...), then call CreatePivotTable on that cache with a destination cell and a name, and set the Orientation of the fields you need.

Why do I get "Unable to get the PivotFields property of the PivotTable class"?

No field has exactly that name. Usually the source header has a hidden trailing space, or the field is in the Values area under a caption such as Sum of Amount. Print SourceName and Name for every field to see the real names.

Can two PivotTables share the same PivotCache?

Yes. Reports built from the same cache show the same CacheIndex, refresh together and share grouping, which keeps the file small but means grouping one report changes the other.

How do I list all PivotTables in a workbook with VBA?

Loop For Each ws In ThisWorkbook.Worksheets and inside it For Each pt In ws.PivotTables. Reading pt.Name, pt.CacheIndex and pt.PivotCache.RecordCount gives a quick inventory.

Why does my PivotTable not show new rows after a refresh?

The cache was built from a fixed range, so refresh re-reads only that range. Point the cache at an Excel Table, or rebuild it from the current data region, so new rows are included.

Keep going: PivotTables with VBA

This free lab is lesson 1 of 7. Unlock the other 6 hands-on labs, the final exam and your certificate for a one-time โ‚ฌ9.90.

  1. Building the PivotCache
  2. Creating the PivotTable in Code
  3. Adding Row, Column and Data Fields
  4. Changing the Summary Function and Number Format
  5. Filtering a PivotTable
  6. Refreshing, Rebuilding and Deleting

Buy course โ€” โ‚ฌ9.90 See the full course

Knowledge check

Two PivotTables in a workbook report the same CacheIndex. You group the date field of one of them by month. What happens to the other?

Continues in this course
  • Building the PivotCache
  • Creating the PivotTable in Code
  • Adding Row, Column and Data Fields
  • Changing the Summary Function and Number Format
  • Filtering a PivotTable
  • Refreshing, Rebuilding and Deleting

Buy the course to unlock the remaining 6 lessons, the exam and the certificate.

Buy course โ€” โ‚ฌ9.90