使用VBA添加计算字段

时间:2014-11-17 09:49:52

标签: vba excel-2010 pivot-table

我正在尝试将计算字段添加到在VBA(Excel 2010)中创建的数据透视表中。数据透视表正在运行,一切都在显现 - 除了完全没有的计算字段外。

我使用的代码如下:

    Sub Create_Pivot_Table_for_chart2()
 Dim wsnew As Worksheet
 Dim objPivotcache As PivotCache
 Dim objPivotTable As PivotTable

'Adding new worksheet
 Set wsnew = Worksheets.Add
 wsnew.Name = "Test5"

'Creating Pivot cache
 Set objPivotcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'datasheet'!B1:BX1000")

'Creating Pivot table
 Set objPivotTable = objPivotcache.CreatePivotTable(wsnew.Range("A1"))

'Setting Fields
 With objPivotTable
 'set row field
 With .PivotFields("Prosperator")
 .Orientation = xlRowField
 .Position = 1
 End With

 'set column field
 With .PivotFields("Business Name")
 .Orientation = xlRowField
 .Position = 2
 End With

  'set calculated field
 .CalculatedFields.Add "TOGrowth%", "= ('ITD Average'- 'Pre-ignition T/O')/'Pre-ignition T/O'"

 'set data field
 .AddDataField .PivotFields("Pre-ignition T/O"), "PI T/O", xlSum
 .AddDataField .PivotFields("ITD Average"), "ITD", xlSum


 End With
END SUB

由于

1 个答案:

答案 0 :(得分:2)

查看您的代码,您尚未将计算字段作为数据字段添加到数据透视表中。

您需要在创建字段后添加以下代码行:

.PivotFields("TOGrowth%").Orientation = xlRowField