首页 > 解决方案 > 错误代码:当相同的代码适用于不同的数据透视表时,“无法获取工作表类的数据透视表属性”

问题描述

我正在编写一个创建多个数据透视表的宏。除了 1 个表之外的所有表都运行良好,但我收到以下表的运行时错误代码:unable to get the pivottables property of the worksheet class

Dim PT As Excel.PivotTable
    Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
            "GFCID!R1C1:R117200C129", Version:=xlPivotTableVersion14).CreatePivotTable( _
            TableDestination:="'source'!R1C1", TableName:="Banking Book Pivot", _
            DefaultVersion:=xlPivotTableVersion14)

    With PT.PivotFields( _
        "IRU")
        .Orientation = xlRowField
        .Position = 1
    End With
    
'    ActiveSheet.PivotTables("Banking Book Pivot").AddDataField ActiveSheet.PivotTables( _
'        "Banking Book Pivot").PivotFields("GFCID"), "Count of GFCID", xlCount
    
'    PT.AddDataField ActiveSheet.PivotTables( _
'        "Banking Book Pivot").PivotFields("GFCID"), "Count of GFCID", xlCount

'    With ActiveSheet.PivotTables("Banking Book Pivot").PivotTables("Banking Book Pivot").PivotFields("GFCID" & Chr(10) & "Count")
'        .Orientation = xlDataField
'        .Function = xlCount
'        .Name = "Count of GFCID"
'    End With

我已经尝试了被注释掉的三个代码中的每一个,它们都得到了相同的错误。前两个代码与宏中的其他数据透视表一起使用。该数据透视表的数据集比其他数据集大得多,但我认为这不会产生影响。

标签: excelvbapivot

解决方案


不要使用ActiveSheet. 使用PT

With PT
    .AddDataField .PivotFields("GFCID"), "Count of GFCID", xlCount
End With

推荐阅读