【问题标题】:Add a calculated field in Pivot Table在数据透视表中添加计算字段
【发布时间】:2017-10-18 14:43:35
【问题描述】:

我创建了一个数据透视表,我想在其中添加一列,它将打印数据透视表的其他两列之间的差异(值)。我将提供与构建数据透视表相关的代码部分。很明显,我在它的最后部分尝试了一些东西,但它不会打印任何东西。它运行,但它只是不打印任何东西。它只正确打印数据透视表,而不是新列。

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

【问题讨论】:

标签: vba excel pivot-table


【解决方案1】:

添加计算字段后,您需要将其方向设置为 xlDataField 以使其在数据透视表上可见。

试试这样的...

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

【讨论】:

  • 很好用,但实际上它并没有打印出我想要的结果。我试图修复列的公式,新的公式就是这个.. .CalculatedFields.Add "Diff ", "=GETPIVOTDATA('每月$/SU预测',$A$15,'T-Lane','雅典到希腊')-GETPIVOTDATA('每月$/SU实际',$A$15,'T-Lane' ,'雅典到希腊')" .PivotFields("Diff").Orientation = xlDataField
  • 但是,这个新公式有一个错误,因为它说无法设置属性
  • 在您手动创建计算字段然后分析代码时记录宏,这会给您一个想法,然后根据您的要求进行调整。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多