使用VBA创建数据透视表时出错

时间:2018-02-07 20:25:27

标签: excel vba excel-vba

当我运行下面的VBA代码来创建数据透视表时,运行宏时出现“无效的过程或调用参数错误”。错误发生在“设置PT”区域。

我已经定义了工作表对象,但我也尝试调整“表格目的地”以直接引用工作表,但我仍然得到同样的错误。

知道可能导致错误的原因是什么?

With wsData
    Dim PTCache As PivotCache
    Dim PT As PivotTable

    'Creates the Cache
    Set PTCache = ActiveWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=.Range("A1").CurrentRegion)

    'Creates pivot table
    Set PT = wsPivot.PivotTables.Add( _
        PivotCache:=PTCache, _
        TableDestination:=wsPivot)

    'Defines fields
    With PT
        .PivotFields("Field 1").Orientation = xlRowField
        .PivotFields("Field 2").Orientation = xlRowField
        .PivotFields("Field 3").Orientation = xlRowField
        .AddDataField .PivotFields("Field 4"), "Field 4", xlCount
        .TableStyle2 = "PivotStyleMedium2"
    End With
End With

1 个答案:

答案 0 :(得分:0)

我发现了这个问题,而不是使用我ActiveWorkbook ThisWorkbook来构建数据透视缓存。

以下代码运行时没有错误:

With wsData
Dim PTCache As PivotCache
Dim PT As PivotTable

'Creates the Cache
Set PTCache = ThisWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=.Range("A1").CurrentRegion)

'Creates pivot table
Set PT = wsPivot.PivotTables.Add( _
    PivotCache:=PTCache, _
    TableDestination:=wsPivot)

'Defines fields
With PT
    .PivotFields("Field 1").Orientation = xlRowField
    .PivotFields("Field 2").Orientation = xlRowField
    .PivotFields("Field 3").Orientation = xlRowField
    .AddDataField .PivotFields("Field 4"), "Field 4", xlCount
    .TableStyle2 = "PivotStyleMedium2"
End With
End With