Excel VBA Pivot Table Properties: A Practical Guide
In this article
You control a pivot table from VBA by referencing the right object at the right level, because pivot properties are spread across four nested objects: PivotTable (the whole report), PivotField (rows, columns, filters), PivotCell (one cell inside the report) and PivotCache (the memory copy of the source data). Set the wrong one and you get error 1004 or a change that silently does nothing. The shortest working set is: name the sheet and pivot explicitly, set PivotFields orientation to xlRowField or xlColumnField to build the layout, then adjust presentation properties such as CompactLayoutRowHeader, RepeatItemsOnEachPrintedPage and EnableDrilldown. The steps below cover each level in the order that avoids most errors.
What You'll Need
- Excel on Windows or Mac with macros enabled; VBA is not available in Excel for the web or the mobile apps.
- A workbook with VBA project access. The Developer tab must be visible: right-click the ribbon and choose Customize the Ribbon, then tick Developer. On Mac this is Excel > Preferences > Ribbon & Toolbar.
- A source table or range with headers, and at least one existing pivot table to test against, or permission to create one in code.
- Optionally Excel's Macro Recorder, which is the fastest way to discover the exact property names for your version of Excel.
Step-by-Step
- Open the VBA editor and add a module. Press Alt+F11 (on Mac, Option+F11 or Tools > Macro > Visual Basic Editor). In the editor, right-click the project and choose Insert > Module. Write your code there, not in a sheet module, so it can be called from anywhere. Menu labels can differ slightly between versions and platforms.
- Declare explicit object variables. Turn on Option Explicit at the top of the module via Tools > Options > Require Variable Declaration. Declare
Dim pt As PivotTableandDim pf As PivotField. Referring toActiveSheet.PivotTables(1)everywhere works but breaks the moment someone selects another sheet, so always capture the objects first. - Point at the pivot table by name, not index. A pivot table's name is set in PivotTable Analyze > PivotTable > Options on the ribbon, and in VBA as
pt.Name. UseSet pt = Worksheets("Report").PivotTables("PivotTable1"). You can rebuild the whole pivot from its cache at any time withpt.RefreshTable, which keeps the existing layout. - Set the data source level first. The cache is created when the pivot is created:
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Data!A1:F500"). Then attach it:pc.CreatePivotTable TableDestination:="Report!A3", TableName:="SalesPivot". Properties on the cache, such asRefreshOnFileOpenandMissingItemsLimit, apply to every pivot table sharing that cache, which is a common surprise. - Build the layout through PivotFields. Set orientation and position explicitly:
pt.PivotFields("Region").Orientation = xlRowField,pt.PivotFields("Region").Position = 1,pt.PivotFields("Month").Orientation = xlColumnField. For values, usept.AddDataField pt.PivotFields("Amount"), "Total Amount", xlSum. For report filters usexlPageField, and callpt.PivotFields("Region").ClearAllFiltersbefore selecting items. - Control layout and totals on the PivotTable object. Useful, well-established properties:
pt.RowAxisLayout xlTabularRoworpt.RowAxisLayout xlCompactRowfor the overall style;pt.CompactLayoutRowHeaderto rename the compact row label;pt.RepeatAllLabels xlRepeatLabelsto repeat outer row labels;pt.ShowTableStyleRowStripes = Trueandpt.TableStyle2for banding and styling;pt.RowGrand = Falseorpt.ColumnGrand = Falseto hide grand totals. Setpt.PrintTitles = Trueto repeat column labels on each printed page. - Format numbers and subtotals on each data field. Data fields are pivot fields with
Orientation = xlDataField. Usepf.NumberFormat = "#,##0.00"andpf.Function = xlAverage. To show or hide subtotals, setpt.PivotFields("Region").Subtotals(1) = Trueto switch automatic subtotals on andFalseto hide them. To change a field header caption, setpf.Caption, and remember it must stay unique. - Adjust refreshing and interactivity.
pt.RefreshTablerefreshes one pivot;Workbook.RefreshAllrefreshes everything including Power Query connections, which can be slow. Disable automatic updating during bulk edits withApplication.ScreenUpdating = Falseand restore it at the end, then turn offpt.EnableDrilldown = Falseif you want to stop users double-clicking into detail rows. - Set PivotCell properties only for reading. A
PivotCellexposesPivotCellType,RowItems,ColumnItemsandDataField. These are read-only reference properties, useful for checks like "did the user click a data cell or a header?". Do not try to write a value to a pivot cell; that raises an error because the cells belong to the report structure. - Test against a copy of the workbook. Run the macro on a duplicated file first. Step through with F8 and watch the Locals window so you can see exactly which object returned Nothing. Once it runs cleanly, wire it to a button from the Developer tab: Insert > Form Controls > Button, then choose the macro.
Common Mistakes
- Using the wrong collection.
PivotItemsbelongs to a field, not to the pivot table, andDataFieldsbelongs to the pivot table, not the cache. Mixing these up produces "unable to get the property" errors. - Referring to the active sheet. Any macro that assumes the pivot is on the active sheet fails as soon as a user clicks elsewhere. Always qualify with the worksheet object.
- Setting options on a shared cache. Turning on or off cache-level settings changes every pivot based on that source, not just the one you are looking at.
- Adding the same data field twice. A caption must be unique across the report, so use a distinct name such as "Amount Sum" rather than reusing "Amount".
- Forgetting the refresh. Layout properties apply immediately, but values only reflect new data after a refresh call, and a cached pivot can display stale figures for a long time.
- Hard-coded source ranges. A fixed address stops covering new rows. Use a table name as the source data, or compute the last row dynamically.
Tips
- Record a macro, change one setting by hand, stop recording, then read the generated code. It reveals the exact property and constant names for your build.
- Use the Locals window (View > Locals) to expand pivot objects and browse the properties that actually exist rather than guessing.
- Wrap routines with error handling that restores
ScreenUpdatingandEnableEventsin the exit path, or Excel stays in a strange state after a crash. - Keep one helper function that finds a pivot by name and returns Nothing rather than raising an error; callers can then test for it cleanly.
- Prefer table-based sources so the cache range grows automatically and you never edit source strings again.
Troubleshooting
If a property assignment fails with run-time error 1004, first confirm the object exists and is spelled correctly; a missing field name throws the same error as a wrong property. Print the field names with a loop over pt.PivotFields to see the real names, including any trailing spaces in the header.
If the macro runs but nothing changes on screen, check that you are not writing to a read-only property, that ScreenUpdating is back on, and that you are looking at the right sheet and pivot name. If values are wrong, refresh the pivot table and refresh the underlying connection.
If the code works on your machine and not a colleague's, look for version or platform differences such as 32-bit versus 64-bit Office, or properties that exist only in newer builds. Mac Excel supports much of the object model but some Windows-only options are absent. Keep an On Error handler that logs the property name so the failing line is obvious on their machine too.
As a last resort, save a copy, rebuild the pivot manually, compare the two, and record the manual steps to find the property you missed.
Frequently Asked Questions
Can I change pivot table properties without refreshing the source?
Layout, formatting and display properties apply immediately. Values and item lists come from the cache, so they need a refresh to change.
Why does my macro change every pivot table instead of one?
You are probably writing to the PivotCache or to a workbook-level collection. Move the assignment to a specific PivotTable object.
Does VBA work in Excel for the web?
No. VBA runs only in the desktop versions of Excel on Windows and Mac. The browser and mobile versions cannot execute macros.
How do I find the name of a pivot table?
Click inside it and look at the PivotTable Analyze tab, or read the name in PivotTable Options > PivotTable Name.
Can I set a pivot table's properties without creating it in code first?
Yes. Reference an existing pivot by worksheet and name, then change its fields and properties exactly as if you had built it.