简体   繁体   English

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

[英]Looping PivotTable through Worksheets - FAILS when AddDataField

I have processed multiple modules to the overall script I am working on and this is the only component that is not working well for me. 我已经处理了要处理的全部脚本的多个模块,这是唯一对我不利的组件。 I can get the initial setup of the PivotTable to work, but when added a Sum field it goes awry. 我可以使数据透视表的初始设置正常工作,但是添加“求和”字段后会出错。 Any feedback on the below would be greatly appreciated. 关于以下任何反馈将不胜感激。

    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

The part of code the gives me an error is as follows: 给我错误的代码部分如下:

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

Error as follows: Run-time error '1004': Unable to get the PivotFields property of the PivotTable class 错误如下:运行时错误'1004':无法获取PivotTable类的PivotFields属性

Peter - As you stated I needed to process this as a manual sequence and review the code. 彼得-如您所述,我需要将其作为手动序列进行处理并查看代码。 I just did that and found that the line in question needed to be adapted to be: 我只是这样做,发现有问题的行需要修改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM