数据透视表扩展"值" VBA

时间:2016-07-14 22:41:28

标签: excel vba excel-vba for-loop pivot-table

我正在尝试自动将字段添加到已创建的数据透视表中。字段将是"期间1和#34的总和; ......"期间360"的总和。我已经有1-60期,但是缺少61-360。手动拖动300次会很痛苦。所以我写了一个宏,但是我得到了错误:  无法获取透视字段类的透视项属性

由于数据透视表已经创建(它是一个有很多格式怪癖的大桌子),我不想改变任何东西。我只想将句点添加为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 36​​0时段

' 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

1 个答案:

答案 0 :(得分:0)

您从宏录制中生成了大量无关代码。此外,您可能会收到"应用程序定义的错误或对象定义错误"消息,因为您尝试添加的一个或多个字段已存在。

我会建议这个......

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