Chapter 11
Using VBA to Create Pivot Tables
240
11
In Excel 2000 and newer, you first build a pivot cache object to describe the input area of
the data:
Dim WSD As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PRange As Range
Dim FinalRow As Long
Dim FinalCol As Long
Set WSD = Worksheets(“PivotTable”)
‘ Delete any prior pivot tables
For Each PT In WSD.PivotTables
PT.TableRange2.Clear
Next PT
‘ Define input area and set up a Pivot Cache
FinalRow = WSD.Cells(Rows.Count, 1).End(xlUp).Row
FinalCol = WSD.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol)
Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:=PRange)
After defining the pivot cache, use the
CreatePivotTable
method to create a blank pivot
table based on the defined pivot cache:
Set PT = PTCache.CreatePivotTable(TableDestination:=WSD.Cells(2, Fi 2), _
TableName:=”PivotTable1”)
In the
CreatePivotTable
method, you specify the output location and optionally give the
table a name. After running this line of code, you have a strange-looking blank pivot table,
like the one shown in Figure 11.3. You now have to use code to drop fields onto the table.
If you choose the Defer Layout Update setting in the user interface to build the pivot table,
Excel does not recalculate the pivot table after you drop each field onto the table. By default
in VBA, Excel calculates the pivot table as you execute each step of building the table. This
could require the pivot table to be executed a half-dozen times before you get to the final
result. To speed up your code execution, you can temporarily turn off calculation of the
pivot table by using the
ManualUpdate
property:
PT.ManualUpdate = True
Although the Excel user interface has new names for the various sections of a pivot table,VBA code
will continue to refer to the old names. Microsoft had to use this choice, otherwise millions of lines
of code would stop working in Excel 2007 when they referred to a page field instead of a filter field.
While the four sections of a pivot table in the Excel user interface are Report Filter, Column Labels,
Row Labels, and Values,VBA continues to use the old terms of Page fields, Column fields, Row fields,
and Data fields.
C A U T I O N
12_0789736012_CH11.qxd 12/11/06 6:26 PM Page 240
Содержание VBA
Страница 60: ......