2014-11-17 80 views
0

正試圖將計算字段添加到在VBA(Excel 2010)中創建的數據透視表中。即將到來的桌子正在工作,一切都顯現出來 - 除了計算的字段完全沒有。使用VBA添加計算字段

我使用的代碼如下:

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 

感謝

回答

2

看你的代碼,您沒有添加計算字段的數據透視表的數據字段。

您需要添加以下代碼行,你所創建的後場:

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

Rried這一點,UT返回錯誤「無法設置透視字段類的方向屬性」。 –

+0

如果添加爲「xldatafield」 –