Excel VBA Pivot Table Formatting: Step-by-Step Guide
In this article
You can format a pivot table with VBA by setting properties on the PivotTable object and its PivotFields, PivotItems, and DataFields. The key is to reference the pivot table reliably (by name or index), then apply number formats, fonts, colors, and layout settings through code. This guide walks you through the exact steps, from creating the pivot table to applying consistent formatting and handling common errors.
What You'll Need
- Excel 2010 or later (the VBA object model is stable across these versions; labels may differ slightly by version or region).
- A workbook containing at least one pivot table (or the source data to create one).
- Basic familiarity with the VBA editor (Alt+F11) and how to insert a module.
- Macro security settings that allow macros to run (you can enable them for the session).
Step-by-Step
- Open the VBA editor and insert a module. Press Alt+F11, then in the Project Explorer right-click your workbook and choose Insert > Module. This is where you will write your formatting code.
- Declare variables for the pivot table and its components. At the top of the module, add:
Dim pt As PivotTableDim pf As PivotFieldDim pi As PivotItemDim df As DataField
This makes your code easier to read and modify. - Set a reference to the pivot table. Use the PivotTables collection of the worksheet. For example:
Set pt = Worksheets("Sheet1").PivotTables(1)
Replace "Sheet1" with your sheet name and adjust the index if you have multiple pivot tables. Alternatively, use the pivot table's name:Worksheets("Sheet1").PivotTables("PivotTable1"). - Apply a built-in style or set table-wide formatting. You can use
pt.TableStyle2 = "PivotStyleLight16"(style names vary by Excel version; check the available styles in the PivotTable Styles gallery). To set font and color for the entire table, usept.TableRange1.Font.Name = "Calibri"andpt.TableRange1.Font.Size = 10. Note that TableRange1 excludes page fields; TableRange2 includes them. - Format the data fields. Loop through each data field and set the number format:
For Each df In pt.DataFieldsdf.NumberFormat = "#,##0.00"Next df
Adjust the format string to suit your data (e.g., "0%" for percentages, "mm/dd/yyyy" for dates). - Format row and column fields. For each pivot field, you can set the layout and subtotal appearance. For example, to set the number format for a row field:
For Each pf In pt.RowFieldspf.NumberFormat = "@"Next pf
Use "@" for text, or a date/number format as needed. - Adjust field layout and subtotals. Set
pf.LayoutForm = xlTabularRowfor a tabular layout, orxlOutlineRowfor outline. To hide subtotals:pf.Subtotals(1) = False(the index corresponds to automatic, custom, etc.; setting the first element to False turns off automatic subtotals). - Format specific pivot items (optional). If you need to highlight a particular item, loop through the PivotItems of a field:
For Each pi In pt.PivotFields("Region").PivotItemsIf pi.Name = "North" Then pi.Font.Bold = TrueNext pi
Be aware that pivot items may not exist if the field is not in the layout; checkpf.Orientation <> xlHiddenfirst. - Set column widths and row heights. Use
pt.TableRange1.Columns.AutoFitto auto-fit columns. For row heights, you can setpt.TableRange1.Rows.RowHeight = 15. - Apply conditional formatting (optional). VBA can add a format condition to the data range. For example:
pt.TableRange1.FormatConditions.AddColorScale ColorScaleType:=3
This adds a 3-color scale. Adjust the range as needed (e.g., only the data body range). - Run the macro and verify. Press F5 or run the macro from the Macros dialog. Check that the formatting applied correctly. If you need to re-run, consider clearing existing formatting first (see Tips).
Common Mistakes
- Referencing the wrong pivot table. Using
PivotTables(1)may point to a different table if you add or delete pivot tables. Use the name instead. - Assuming TableRange1 includes everything. TableRange1 excludes page fields; use TableRange2 if you need to format the entire pivot table including page fields.
- Formatting PivotItems that don't exist. If a field is hidden or an item is not present, referencing it causes an error. Check the field's Orientation and the item's Visible property.
- Forgetting that pivot table formatting can be overwritten. Refreshing the pivot table may reset some formatting. Set
pt.PreserveFormatting = Trueto keep formatting when the pivot table is refreshed. - Using number formats that don't match the data type. Applying a date format to a text field will not work as expected. Verify the field's data type.
Tips
- Use
pt.PreserveFormatting = Trueto maintain formatting after refresh. - To clear existing formatting before applying new, use
pt.TableRange2.ClearFormats(this clears all formatting, including borders and fonts). - Record a macro while formatting a pivot table manually to discover the exact property names and values.
- Use
Withblocks to make your code cleaner and faster. - Test on a copy of your workbook to avoid losing data.
Troubleshooting
If your macro does not work as expected, try these steps in order:
- Check for errors. Run the macro and note the error message and line. Common errors include "Subscript out of range" (wrong sheet or pivot table name) and "Object variable not set" (missing Set statement).
- Verify the pivot table name. In Excel, click the pivot table and look at the PivotTable Name in the Analyze tab (or PivotTable Tools). Use that exact name in your code.
- Ensure the pivot table exists on the specified sheet. If the sheet name is wrong, you'll get an error. Use
Worksheets("Sheet1").PivotTables.Countto check how many pivot tables are on the sheet. - Check for protected sheets or workbooks. Formatting cannot be applied to a protected sheet. Unprotect it first (Review > Unprotect Sheet).
- Refresh the pivot table. If the pivot table is based on external data, refresh it before formatting to ensure all items are present.
- Use the macro recorder. Record your manual formatting steps to see the exact VBA code generated, then adapt it.
Frequently Asked Questions
How do I format a pivot table without affecting the source data?
Pivot table formatting is separate from the source data. Changes made via VBA to the PivotTable object only affect the pivot table's appearance, not the underlying data.
Can I apply conditional formatting to a pivot table with VBA?
Yes, you can use the FormatConditions collection on the pivot table's range. However, be aware that conditional formatting may not survive a pivot table refresh unless you set PreserveFormatting to True.
Why does my formatting disappear after refreshing the pivot table?
By default, pivot tables may lose formatting on refresh. Set pt.PreserveFormatting = True before refreshing to retain formatting.
How do I format multiple pivot tables at once?
Loop through the PivotTables collection of the worksheet or workbook and apply the same formatting code to each. For example: For Each pt In Worksheets("Sheet1").PivotTables ... Next pt.
Can I change the number format of a data field to show thousands separators?
Yes, set the NumberFormat property of the DataField to "#,##0" or "#,##0.00" as needed.
What if I get a "Permission denied" error when running the macro?
This usually means the sheet or workbook is protected. Unprotect it via the Review tab, or adjust the macro to unprotect, format, and reprotect (be cautious with passwords).