VBA创建数据透视表,类型不匹配?我做错了什么



在行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
这对

我有用...

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

警告:如果工作表透视存在,您将收到错误。也许您想将其添加到您的代码中?

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

而不是使用

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 。不过,我还没有检查该语句下方代码的有效性。

最新更新