简体   繁体   中英

Add a calculated field in Pivot Table

I have created a pivot table and I want to add a column in it , in which it will print the difference (in value) between two other columns of the Pivot Table. I will provide the part of my code related to building the pivot table. As it is clear, I have tried something in the last part of it, but it wont print nothing. It runs but it just does not print anything . It only prints the Pivot Table correctly, but not the new column.

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

After adding the Calculated field, you need to set it's orientation to xlDataField to make it visible on the Pivot Table.

Try something like this...

.CalculatedFields.Add "Diff", "= 'Monthly Cost FCST'- 'Monthly Cost Actuals'"
.PivotFields("Diff").Orientation = xlDataField

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM