Pivot Table Run Time Error

ryan8200

Active Member
Joined
Aug 21, 2011
Messages
357
I tried to create pivot table on existing sheets but hitting run time error 13 (type mismatch) . I have changed data and pivot range to reference by address but still not workable. Please refer to my code as below:

VBA Code:
[/

     Dim DSheet As Worksheet
     Dim PCache As PivotCache
     Dim PTable As PivotTable
     Dim Drange As Range
     Dim Prange As Range
     Dim LastRow As Long
     Dim LastCol As Long

    'Define Data Range
     Set DSheet = ThisWorkbook.Worksheets("My")
     LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
     LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
     Set Drange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

    'Define Pivot Cache
    Set Prange = DSheet.Cells(1, 13)
    Set PCache = ActiveWorkbook.PivotCaches.Create _
    (SourceType:=xlDatabase, SourceData:="'" & DSheet.Name & "'!" & Drange.Address(ReferenceStyle:=xlR1C1)). _
    CreatePivotTable(TableDestination:="'" & DSheet.Name & "'!" & Prange.Address(ReferenceStyle:=xlR1C1), _
    TableName:="MyPivotTable")
]
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
Change your ('Define Pivot Cache) code to this:-

VBA Code:
    'Define Pivot Cache
    Set Prange = DSheet.Cells(1, 13)
    Set PTable = ActiveWorkbook.PivotCaches.Create _
        (SourceType:=xlDatabase, SourceData:=Drange). _
        CreatePivotTable(TableDestination:=Prange, _
        TableName:="MyPivotTable")
 
Upvote 0
You should really use ThisWorkbook, not ActiveWorkbook, since that's where the source data is.
 
Upvote 0

Forum statistics

Threads
1,223,237
Messages
6,170,928
Members
452,366
Latest member
TePunaBloke

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top