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.PivotCacheandpt.CacheIndex, and nothing else about the source. - PivotField belongs to a PivotTable. Each column heading of the source becomes a field, and its
Orientationsays 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.
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:
| Row | A: Region | B: Product | C: Amount |
|---|---|---|---|
| 2 | West | Cable | 114 |
| 3 | North | Adapter | 121 |
| 4 | South | Cable | 128 |
| 5 | West | Adapter | 135 |
| 6 | North | Cable | 142 |
| 7 | South | Adapter | 149 |
| โฆ | โฆ | โฆ | โฆ |
| 25 | South | Adapter | 275 |
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:
| Total | Adapter | Cable | Grand Total |
|---|---|---|---|
| North | 736 | 820 | 1,556 |
| South | 848 | 764 | 1,612 |
| West | 792 | 708 | 1,500 |
| Grand Total | 2,376 | 2,292 | 4,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.
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.Createis called on the workbook, because that is where caches live.xlDatabasemeans a range of cells, andCurrentRegionexpands from A1 to the whole block of data.pc.CreatePivotTableis called on the cache, not on the sheet. The cache produces the report and places it at A3, leaving room above for filters.- Setting
Orientationmoves a field into an area, exactly like dragging it in the field list. AddDataFieldputs Amount into Values with the captionTotaland the functionxlSum. 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:
| Sheet | PivotTable | Cache | Records in cache | Last refresh | Field | Sits in |
|---|---|---|---|---|---|---|
| Demo Report 101530 | ptDemo101530 | 1 | 24 | 2026-10-31 10:15 | [Region] | Rows |
| Demo Report 101530 | ptDemo101530 | 1 | 24 | 2026-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
- Open a new workbook and save it straight away as Excel Macro-Enabled Workbook (*.xlsm) with
F12, so the code is not lost. - Press
Alt+F11(Mac:Opt+F11), select the workbook in the Project Explorer and choose Insert โ Module. - Paste both macros from the lab,
MakePivotDemoandAuditPivotTables, into the module. Keep a singleOption Explicitat the top. - Click inside
MakePivotDemoand pressF5. Two new sheets appear: Demo Data and Demo Report, each with a time stamp in the name. - 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.
- 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. - Press
Alt+F8, chooseAuditPivotTablesand click Run. The Pivot Audit sheet lists every field with its placement, cache and record count. - Add a row 26 to the data sheet and press
Alt+F5on the report to refresh it. Because the cache was built from the oldCurrentRegion, the new row is ignored until the source is redefined. Lesson 2 shows how an Excel Table avoids this.
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.
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,Marinstead of one Month field. - A fixed source address.
Range("A1:C25")is right today and wrong next month. Symptom:RecordCountlower 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", xlSumraises 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
CacheIndexin 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.
| Item | Belongs to | What it gives you |
|---|---|---|
wb.PivotCaches.Create(SourceType, SourceData) | Workbook | A new cache from a range or Table |
pc.CreatePivotTable(TableDestination, TableName) | PivotCache | A new report on a sheet |
ws.PivotTables | Worksheet | All reports on that sheet |
pt.PivotFields("Region") | PivotTable | One field by its name |
pf.Orientation | PivotField | xlRowField 1, xlColumnField 2, xlPageField 3, xlDataField 4, xlHidden 0 |
pt.AddDataField field, caption, function | PivotTable | A value field such as xlSum or xlCount |
pt.CacheIndex | PivotTable | Number of the cache the report reads |
pt.PivotCache.RecordCount | PivotCache | Rows in the snapshot |
pt.RefreshDate | PivotTable | When the cache was last refreshed |
pf.SourceName / pf.Name | PivotField | Source column name / caption in the report |
Alt+F5 / Ctrl+Alt+F5 | Excel | Refresh this PivotTable / refresh all |
Alt+F8, F5, Ctrl+G | Excel / VBA editor | Macro 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
RecordCountwith the source row count and itsRefreshDatewith 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 CHF 9.90.
- 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