通过工作表循环数据透视表 - AddDataField时失败

时间:2017-06-20 18:52:30

标签: excel vba pivot-table

我已经处理了多个模块到我正在处理的整个脚本中,这是唯一对我不起作用的组件。我可以让数据透视表的初始设置工作,但是当添加一个Sum字段时它会出错。任何有关下面的反馈将不胜感激。

    Sub PivotChart2()

    Dim LastRow As Long
    Dim ws As Worksheet
    Dim wb As Workbook

Set wb = ActiveWorkbook

For Each ws In wb.Sheets
    If ws.Name = "Sheet1" Or ws.Name = "ZIP_US" Then
        'Do Noathing
    Else

        LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        Set PDATA = Range("$A$1:$F" & LastRow)
        Dim PVTNAME As String
        Dim PT As PivotTable

        PVTNAME = Range("$K$1")

        Sheets(ws.Name).Select


        ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        PDATA, Version:=6).CreatePivotTable TableDestination:= _
        ws.Name & "!R3C10", TableName:=Range("$K$1"), DefaultVersion:=6



        With ActiveSheet.PivotTables(1).PivotFields("STATE")
            .Orientation = xlRowField
            .Position = 1
        End With

        With ActiveSheet.PivotTables(1)
        .AddDataField ActiveSheet.PivotTables(1).PivotFields("SALES"), "Sum of SALES", xlSum
        End With

    End If

Next ws




        'pvt.PivotFields("STATE").Orientation = xlRowField
        'pvt.AddDataField pvt.PivotFields("SALES"), "Sum of SALES", xlSum

End Sub

给我一​​个错误的代码部分如下:

 With ActiveSheet.PivotTables(1)
        .AddDataField ActiveSheet.PivotTables(1).PivotFields("SALES"), "Sum of SALES", xlSum
        End With

错误如下:运行时错误' 1004':无法获取数据透视表类的PivotFields属性

1 个答案:

答案 0 :(得分:0)

彼得 - 如你所说,我需要将其作为手动序列处理并查看代码。我刚刚这样做,发现有问题的线需要适应:

    ActiveSheet.PivotTables(1).AddDataField ActiveSheet.PivotTables( _
        1).PivotFields("SALES"), "Sum of SALES", xlSum