繁体   English   中英

使用VBA创建数据透视表时出现过程错误

[英]Procedure Error when creating a pivot table using VBA

当我运行下面的VBA代码创建数据透视表时,运行宏时出现“无效的过程或调用参数错误”。 错误在“ Set 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

我发现了问题,而不是从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

暂无
暂无

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

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