我創建了一個數據透視表,並且我想在其中添加一列,在該列中將顯示數據透視表的兩個其他列之間的差異(以數值表示)。我將提供與構建數據透視表相關的代碼部分。很明顯,我在最後部分嘗試了一些東西,但它不會打印任何東西。它運行,但它只是不打印任何東西。它只能正確打印數據透視表,但不能打印新列。在數據透視表中添加一個計算的字段
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Application.DisplayAlerts = True
Set DSheet = Worksheets("Budget_Report")
Set PRange = DSheet.Range(Cells(1, 27), Cells.SpecialCells(xlCellTypeLastCell))
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(15, 1), TableName:="PivotTable1")
With ActiveSheet.PivotTables("PivotTable1")
With .PivotFields("T-Lane")
.Orientation = xlRowField
.Position = 1
.Subtotals(1) = True
.Subtotals(1) = False
End With
With .PivotFields("Monthly Cost FCST")
.Orientation = xlDataField
.Position = 1
.Function = xlAverage
.NumberFormat = "0.00"
.Caption = "Monthly Cost Forecast"
End With
With .PivotFields("Monthly Vol FCST")
.Orientation = xlDataField
.Position = 2
.Function = xlAverage
.NumberFormat = "0.00"
.Caption = "Monthly Vol Forecast"
End With
With .PivotFields("Monthly $/SU FCST")
.Orientation = xlDataField
.Position = 3
.Function = xlAverage
.NumberFormat = "0.00"
.Caption = "Monthly $/SU Forecast"
End With
With .PivotFields("Monthly Cost Actuals")
.Orientation = xlDataField
.Position = 4
.Function = xlSum
.NumberFormat = "0.00"
.Caption = "Monthly Cost Actual"
End With
With .PivotFields("Monthly Vol Actuals")
.Orientation = xlDataField
.Position = 5
.Function = xlSum
.NumberFormat = "0.00"
.Caption = "Monthly Vol Actual"
End With
With .PivotFields("Monthly $/SU Actuals")
.Orientation = xlDataField
.Position = 6
.Function = xlAverage
.NumberFormat = "0.00"
.Caption = "Monthly $/SU Actual"
End With
.CalculatedFields.Add "Diff", "= 'Monthly Cost FCST'- 'Monthly Cost Actuals'"
End With
檢查https://stackoverflow.com/a/26970322/7889129 – Maddy
你嘗試看到宏錄製生產什麼,然後調整? – QHarr