VBA to create pivot table, type mismatch? What am I doing wrong?

Getting type mismatch on the line tabledestination:=("pivot!A3")
I want to add a sheet and name it "Pivot" and create a pivot table on this 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
source share
2 answers

It 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 own way,

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 PIVOT sheet exists, you will receive an error message. 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"
+1
source

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"))

Sheets("Pivot").Activate PivotCache:=Pcache. .

0

Source: https://habr.com/ru/post/1548376/


All Articles