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

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
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,212,927
Messages
6,110,726
Members
448,294
Latest member
jmjmjmjmjmjm

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