241
Building a Pivot Table in Excel VBA
You can now run through the steps needed to lay out the pivot table. In the
.AddFields
method, you can specify one or more fields that should be in the row, column, or filter area
of the pivot table.
The
RowFields
parameter enables you to define fields that appear in the Row Labels layout
area of the PivotTable Field List. The
ColumnFields
parameter corresponds to the Column
Labels layout area. The
PageFields
parameter corresponds to the Report Filter layout area.
The following line of code will populate a pivot table with two fields in the row area and
one field in the column area.
‘ Set up the row & column fields
PT.AddFields RowFields:=Array(“Business Segment”, “Product”), _
ColumnFields:=”Region”
To add a field such as Revenue to the values area of the table, you change the
Orientation
property of the field to be
xlDataField
.
Getting a Sum Instead of a Count
Excel is smart. When you build a report with revenue, it assumes you want to sum the rev-
enue. But there is a problem. Say that one of the revenue cells is blank. When you build the
pivot table, even though 99.9% of fields are numeric, Excel assumes you have alphanumeric
data and offers to count this field. This is annoying. It seems to be an anomaly that, on one
hand, you are expected to make sure that 100% of your cells have numeric data, but on the
other hand, the results of the pivot table are often filled with non-numeric blank cells.
When you build the pivot table in the Excel interface, you should take care in the Values
drop zone to notice that the field reads Count of Revenue instead of Sum of Revenue. At
that point, the right course of action is to go back and fix the data, but what people usually
do is double-click the Count of Revenue button and change it to Sum of Revenue.
In VBA, you should always explicitly define that you are creating a sum of revenue by
explicitly setting the
Function
property to
xlSum
:
11
Figure 11.3
Immediately after you
use the
CreatePivotTable
method, Excel gives you
a four-cell blank pivot
table that is not very
useful.
12_0789736012_CH11.qxd 12/11/06 6:26 PM Page 241
Содержание VBA
Страница 60: ......