【问题标题】:VBA to Create PivotTable, Type Mismatch? What Am I Doing Wrong?VBA 创建数据透视表,类型不匹配?我究竟做错了什么?
【发布时间】:2013-09-21 00:26:33
【问题描述】:

获取类型不匹配就行了tabledestination:=("pivot!A3")
我想添加一个工作表并将其命名为“数据透视表”并在该工作表上创建数据透视表。

Dim pt As PivotTable
Dim Pcache As PivotCache
Sheets.add.name = "Pivot"
Sheets("DATA").Select
Set Pcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Cells(1, 1).CurrentRegion)
Set pt = ActiveSheet.PivotTables.Add(PivotCache, tabledestination:=("pivot!A3"))
    With pt
        PivotFields.Subtotals(1) = False
        .InGridDropZones = True
        .RowAxisLayout xlTabularRow
        .PivotFields("Apple").Orientation = xlRowField
        .PivotFields("Apple Qty").Orientation = xlDataField
        End With

【问题讨论】:

    标签: vba excel pivot pivot-table


    【解决方案1】:

    这对我有用...

    Sub Sample()
        Dim pt As PivotTable
        Sheets.Add.Name = "Pivot"
    
        With ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
            SourceData:=Sheets("DATA").Cells(1, 1).CurrentRegion)
    
            Set pt = .CreatePivotTable(TableDestination:="Pivot!R3C1")
        End With
    
        '~~> Rest of Code
    End Sub
    

    或者如果你想按照自己的方式去做,那么

    Sub Sample()
        Dim pt As PivotTable
        Dim Pcache As PivotCache
    
        Sheets.Add.Name = "Pivot"
    
        Set Pcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, _
        Sheets("DATA").Cells(1, 1).CurrentRegion)
    
        Set pt = Pcache.CreatePivotTable(tabledestination:=("Pivot!R3C1"))
    
        '~~> Rest of the code
    End Sub
    

    注意:如果工作表 PIVOT 存在,您将收到错误消息。也许您想将此添加到您的代码中?

    Application.DisplayAlerts = False
    On Error Resume Next
    Sheets("Pivot").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True
    Sheets.Add.Name = "Pivot"
    

    【讨论】:

      【解决方案2】:

      而不是使用

      Set pt = ActiveSheet.PivotTables.Add(PivotCache, tabledestination:=("pivot!A3"))
      

      我用它来前进:

      Sheets("Pivot").Activate
      Set pt = ActiveSheet.PivotTables.Add(PivotCache:=Pcache, TableDestination:=Range("A3"))
      

      注意添加了Sheets("Pivot").ActivatePivotCache:=Pcache。不过,我还没有检查该语句下方代码的有效性。

      【讨论】:

        猜你喜欢
        • 2013-08-06
        • 1970-01-01
        • 2016-07-18
        • 1970-01-01
        • 1970-01-01
        • 2019-12-23
        • 2014-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多