[英]Pivot Table Expand “Values” VBA
我試圖自動添加字段到已創建的數據透視表。 這些字段將是“期間1的總和”......“期間360的總和”。 我已經有1-60期,但是缺少61-360。 手動拖動300次會很痛苦。 所以我寫了一個宏,但是我得到了錯誤: 無法獲得pivot字段類的pivot items屬性
由於數據透視表已經創建(這是一個有很多格式怪癖的大表),我不想改變任何東西。 我只想將句點添加為period61-period360的值之和。
我附上了我的代碼。 任何人都可以給我的任何幫助都會非常感激,因為我不知道我做錯了什么而且我不想太沮喪。
非常感謝你提前。
這是我的代碼:
'--------------------- Expand_Pivot_to_360M Macro-------------------'
Sub Expand_Pivot_to_360M()
' Setting Pivot field classes to the "unable to get pivot items property of the pivot field class" error
Sheets("Monthly Summary").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("universe")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("buckets_break")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("pool_name")
.Orientation = xlRowField
.Position = 3
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("gl_company_code")
.Orientation = xlRowField
.Position = 4
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("LEP")
.Orientation = xlRowField
.Position = 5
End With
循環展開Pivit 360時段
' Using a Loop to Expand Pivot for 360 periods
Dim i As Integer
For i = 61 To 360 ' start at period 61 since periods 1 to 60 already include in pivot
Sheets("Monthly Summary").Select
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Period_i"), "Sum of Period_i", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Period_i")
.Caption = "Count of Period_i"
.Function = xlCount
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Count of Period_i")
.Caption = "Sum of Period_i"
.Function = xlSum
End With
Next i
End Sub
您有很多從宏錄制生成的無關代碼。 此外,您可能會收到“應用程序定義或對象定義的錯誤”消息,因為您嘗試添加的一個或多個字段已存在。
我會建議這個......
Dim i as Integer
Dim found as Boolean
Dim aPItem as PivotItem
With Sheets("Monthly Summary").PivotTables("PivotTable1")
For i = 61 to 360
found = false
For Each aPItem In .DataPivotField.PivotItems 'Check field not already there
If aPItem.Caption = "Sum of Period_" & i Then
found = True
Exit For
End If
Next aPItem
If Not found then 'add field
.AddDataField .PivotFields("Period_" & i), "Sum of Period_" & i, xlSum
End If
Next i
End With
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.