VBA to Create PivotTable, Type Mismatch? What Am I Doing Wrong?

瘦欲@ 提交于 2020-01-05 03:36:06

问题


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.



来源:https://stackoverflow.com/questions/18835056/vba-to-create-pivottable-type-mismatch-what-am-i-doing-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!