I’ve posted several examples of manipulating pivot tables with VBA, for example, Dynamic Chart using Pivot Table and VBA and Update Regular Chart when Pivot Table Updates. These examples included specific procedures, and the emphasis was on the results of the manipulation.
I thought it would be helpful to show some of the mechanics of programming with pivot tables. One important part of this is referencing the various ranges within a pivot table by their special VBA range names (which are actually properties of the Pivot Table object).
I’ll illustrate these special ranges using this simple pivot table, which comes from an example formerly available on the Microsoft web site (I can no longer locate it).
In VBA, you can reference a pivot table using this code in a procedure:
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables(1)
I’ve highlighted the various ranges using the indicated VBA commands.
TableRange1
pt.TableRange1.Select
TableRange2
pt.TableRange2.Select
RowRange
pt.RowRange.Select
ColumnRange
pt.ColumnRange.Select
DataLabelRange
pt.DataLabelRange.Select
DataBodyRange
pt.DataBodyRange.Select
PageRange
pt.PageRange.Select
Pivot Field LabelRange
pt.PivotFields("Years").LabelRange.Select
PivotField DataRange
pt.PivotFields("Years").DataRange.Select
Pivot Item LabelRange
pt.PivotFields("Years").PivotItems("2004").LabelRange.Select
Pivot Item DataRange
pt.PivotFields("Years").PivotItems("2004").DataRange.Select
pt.PivotFields("Order Date").PivotItems("Feb").DataRange.Select
Pivot Field DataRange
The next few examples show the same ranges as above, after pivoting the table’s Years field from the columns area to the rows area.
pt.PivotFields("Years").DataRange.Select
Pivot Item LabelRange
pt.PivotFields("Years").PivotItems("2004").LabelRange.Select
Pivot Item DataRange
pt.PivotFields("Years").PivotItems("2004").DataRange.Select
Complex Range
If a particular range isn’t specifically defined with a VBA property, you can use VBA range-extending properties EntireColumn and EntireRow and range operators Union and Intersect to define the range. For example:
Intersect(pt.PivotFields("Years").Pivotitems("2004").DataRange.EntireRow, pt.PivotFields("Order Date").DataRange).Select
Update
A follow-up post shows how to use this new skill to Create and Update a Chart Using Only Part of a Pivot Table’s Data.