2017-10-18 90 views
0

我創建了一個數據透視表,並且我想在其中添加一列,在該列中將顯示數據透視表的兩個其他列之間的差異(以數值表示)。我將提供與構建數據透視表相關的代碼部分。很明顯,我在最後部分嘗試了一些東西,但它不會打印任何東西。它運行,但它只是不打印任何東西。它只能正確打印數據透視表,但不能打印新列。在數據透視表中添加一個計算的字段

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 
+0

檢查https://stackoverflow.com/a/26970322/7889129 – Maddy

+0

你嘗試看到宏錄製生產什麼,然後調整? – QHarr

回答

2

添加計算字段後,您需要將其方向設置爲xlDataField,以使其在透視表中可見。

嘗試這樣的事情...

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

偉大的工作,但實際上它並不打印我想要的結果..我試圖修復列的公式和工作的新公式是這一個.. .CalculatedFields.Add「Diff」,「= GETPIVOTDATA ('每月$/SU預測',$ A $ 15,'T-Lane','雅典到希臘') - GETPIVOTDATA('每月$/SU實際',$ A $ 15,'T-Lane','雅典到希臘')「 .PivotFields(」Diff「)。Orientation = xlDataField –

+0

但是,這個新公式有錯誤,因爲它說無法設置屬性 –

+0

記錄宏,而您手動創建計算的字段,然後分析代碼,這將給你一個想法,然後根據你的要求調整它。 – sktneer

相關問題