Smart Systems for Home

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

How to Create a Pivot Table in VBA (Step-by-Step)

· 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

Creating a pivot table in VBA lets you automate the whole process: you supply the source data range, the destination cell, and the fields you want, and the macro builds the pivot table in one run. This is ideal when you need the same report every day or week. Before you start, make sure your data is in a contiguous range with headers in the first row, and that you have a blank area on the worksheet where the pivot table will be placed. The steps below use the standard Excel object model and work in Excel 2016 and later.

What You'll Need

  • A workbook with the source data already entered (no blank rows or columns in the range).
  • The Developer tab visible in the Ribbon (if not, right-click the Ribbon, choose Customize the Ribbon, and tick Developer).
  • Basic familiarity with the Visual Basic Editor (opening it with Alt+F11).

Step-by-Step

  1. Open the Visual Basic Editor. Press Alt+F11 in Excel to open the VBA editor. If you prefer, go to the Developer tab and click “Visual Basic”.
  2. Insert a new module. In the VBA editor, click Insert > Module. This creates a blank code window where you will paste or type the macro.
  3. Declare the required variables. At the top of the module, type the following lines (this is the standard structure):
    Dim SourceData As Range
    Dim PivotCache As PivotCache
    Dim PivotTable As PivotTable
    Dim DestCell As Range

    These variables will hold the source range, the pivot cache, the pivot table object, and the destination cell.
  4. Set the source data range. Use Set SourceData = ThisWorkbook.Sheets("Sheet1").Range("A1:D100") — replace the sheet name and range with your own. To make it dynamic, you can use Range("A1").CurrentRegion if your data is surrounded by blank rows/columns and starts at A1.
  5. Set the destination cell. Use Set DestCell = ThisWorkbook.Sheets("Sheet1").Range("F3") (or any empty cell where you want the pivot table to appear). Make sure there is enough blank space below and to the right of that cell.
  6. Create the pivot cache. The pivot cache is an in-memory snapshot of your data. Use:
    Set PivotCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SourceData)
    This works for a normal range; if your data is in a table (ListObject), use SourceData:=SourceData.Parent.ListObjects(1).Range instead.
  7. Create the pivot table. Use:
    Set PivotTable = PivotCache.CreatePivotTable(TableDestination:=DestCell, TableName:="MyPivot")
    Replace “MyPivot” with a unique name (no spaces). This places an empty pivot table at the destination.
  8. Add fields to the pivot table. You add fields by referencing the pivot table’s PivotFields collection. For example, to put a field called “Category” in the Rows area, use:
    With PivotTable
    .PivotFields("Category").Orientation = xlRowField
    .PivotFields("Sales").Orientation = xlDataField
    End With

    Repeat for each field you need. For a data field, you can also set the summary function (Sum, Count, Average) via .Function = xlSum after setting the orientation.
  9. Run the macro. Press F5 while the cursor is inside the macro, or close the editor and run it from the Developer tab > Macros. Check the destination cell — the pivot table should appear with your chosen fields.
  10. Save the workbook as macro-enabled. When you save, choose “Excel Macro-Enabled Workbook (*.xlsm)” so the code is preserved.

Common Mistakes

  • Using a range that includes blank rows/columns. This breaks the pivot cache and causes a runtime error. Always use CurrentRegion or a fixed range that exactly matches your data.
  • Forgetting to set the destination cell to an empty area. If the destination cell already contains data or another pivot table, Excel may overwrite it or throw an error.
  • Misspelling field names. The PivotFields collection uses the exact header text. A typo gives a runtime error 1004.
  • Using xlRowField for a field that should be in the filter area. The orientation constants are specific: xlRowField, xlColumnField, xlPageField (filter), and xlDataField.
  • Not clearing old pivot tables before rerunning. If you run the macro twice, you’ll get a second pivot table. Add a line to delete the existing one before creating a new one.

Tips

  • Use CurrentRegion for dynamic data. If your data grows, Range("A1").CurrentRegion automatically includes all contiguous rows and columns, so you don’t have to update the range manually.
  • Name your pivot table uniquely. Avoid generic names like “PivotTable1” because Excel may already have a table with that name. Use a prefix like “Pivot_” plus a timestamp if needed.
  • Set the pivot table’s RefreshOnFileOpen property to True if you want it to refresh automatically when the workbook opens: PivotTable.RefreshOnFileOpen = True.
  • Use On Error Resume Next to delete an existing pivot table before creating a new one, but be careful — it can hide other errors. Better to check if the pivot table exists.
  • Record a macro to learn the syntax. Turn on the Macro Recorder, create a pivot table manually, then stop and view the generated code. It gives you the exact field names and orientations.

Troubleshooting

Runtime error 1004: “The PivotTable field name is not valid.” This usually means a header cell is blank or the source range includes blank rows. Check that every column has a header, and that the range does not include entire rows or columns.

Runtime error 91: “Object variable or With block variable not set.” This happens when you try to use a variable before setting it. Ensure you have Set SourceData and Set DestCell before creating the cache.

The pivot table appears but is empty. You created the pivot table but did not add any fields. Check the PivotFields lines — make sure you set the orientation for at least one row or column field and one data field.

The macro works but the pivot table does not refresh when data changes. Pivot tables are snapshots. Use PivotTable.RefreshTable after updating the source data, or set PivotTable.RefreshOnFileOpen = True.

If all else fails, step through the code. Press F8 in the VBA editor to execute line by line. Hover over variables to see their current values. This helps you pinpoint which line causes the error.

Frequently Asked Questions

Can I create a pivot table from a dynamic named range?

Yes. Define a named range with the OFFSET formula (e.g., =OFFSET(Sheet1!$A$1,0,0,COUNTA(Sheet1!$A:$A),COUNTA(Sheet1!$1:$1))), then use that name as the SourceData argument. The pivot cache will use the named range, and refreshing will pick up new rows.

How do I add multiple data fields (e.g., Sum of Sales and Count of Orders)?

Set the orientation to xlDataField for each field. For example, .PivotFields("Sales").Orientation = xlDataField and .PivotFields("Orders").Orientation = xlDataField. You can also change the summary function per field.

How do I put a field in the Report Filter area?

Use Orientation = xlPageField for that field. For example, .PivotFields("Region").Orientation = xlPageField.

Can I set the pivot table layout to Tabular or Compact?

Yes. After creating the pivot table, set PivotTable.RowAxisLayout = xlTabularRow for tabular layout, or xlCompactRow for compact. This must be done after the pivot table exists.

How do I prevent the pivot table from showing blank rows?

Set PivotTable.RowGrand = False to hide grand totals, and set PivotTable.ColumnGrand = False if needed. To hide blank items, set PivotTable.PivotFields("FieldName").ShowAllItems = False.

Is it possible to create a pivot table on a new worksheet?

Yes. Instead of a fixed destination cell, add a new sheet: Set DestCell = ThisWorkbook.Sheets.Add.Range("A3"). This creates a new sheet and places the pivot table at A3 of that sheet.