Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Pivot Table Formatting: Step-by-Step Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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.
  2. Declare variables for the pivot table and its components. At the top of the module, add:
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim pi As PivotItem
    Dim df As DataField
    This makes your code easier to read and modify.
  3. 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").
  4. 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, use pt.TableRange1.Font.Name = "Calibri" and pt.TableRange1.Font.Size = 10. Note that TableRange1 excludes page fields; TableRange2 includes them.
  5. Format the data fields. Loop through each data field and set the number format:
    For Each df In pt.DataFields
    df.NumberFormat = "#,##0.00"
    Next df
    Adjust the format string to suit your data (e.g., "0%" for percentages, "mm/dd/yyyy" for dates).
  6. 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.RowFields
    pf.NumberFormat = "@"
    Next pf
    Use "@" for text, or a date/number format as needed.
  7. Adjust field layout and subtotals. Set pf.LayoutForm = xlTabularRow for a tabular layout, or xlOutlineRow for 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).
  8. 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").PivotItems
    If pi.Name = "North" Then pi.Font.Bold = True
    Next pi
    Be aware that pivot items may not exist if the field is not in the layout; check pf.Orientation <> xlHidden first.
  9. Set column widths and row heights. Use pt.TableRange1.Columns.AutoFit to auto-fit columns. For row heights, you can set pt.TableRange1.Rows.RowHeight = 15.
  10. 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).
  11. 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 = True to 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 = True to 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 With blocks 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:

  1. 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).
  2. 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.
  3. Ensure the pivot table exists on the specified sheet. If the sheet name is wrong, you'll get an error. Use Worksheets("Sheet1").PivotTables.Count to check how many pivot tables are on the sheet.
  4. Check for protected sheets or workbooks. Formatting cannot be applied to a protected sheet. Unprotect it first (Review > Unprotect Sheet).
  5. Refresh the pivot table. If the pivot table is based on external data, refresh it before formatting to ensure all items are present.
  6. 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).