VBA to Create PivotTable, Type Mismatch? What Am I

2019-08-04 08:40发布

问题:

Getting Type Mismatch on the line tabledestination:=("pivot!A3")
I want to add a sheet and name it "Pivot" and create PivotTable on that sheet.

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

回答1:

This worked for me...

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

Or if you want to do it your way then

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

Caution: If the sheet PIVOT exists you will get an error. Maybe you would like to add this to your code?

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


回答2:

Instead of using

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

I used this to move forward:

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

Notice the addition of Sheets("Pivot").Activate and PivotCache:=Pcache. I haven't checked the validity of code below that statement, though.