createpivottable cannot set

mamafich

New Member
Joined
Sep 17, 2013
Messages
3
Hi,

I'm trying to create a pivottable on VBA , I've set my range and pivot cache but I cannot create pivot table, it shows = nothing when I watch its value. At the last row of the pasted code below I receive the error "Run Time error 91, Object Variable not set". I couldn't find what is wrong with the code.

Thanks a lot,


Code:
Dim ws As Worksheet
Dim ptCache As PivotCache
Dim pt As PivotTable
Dim prange As Range
Dim lastrow As Long
Dim lastcol, lastpivot As Long
Dim i, j As Long
Set ws = Worksheets(1)


For Each pt In ws.PivotTables
    pt.TableRange2.Clear
Next pt


lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row
lastcol = ws.Cells(1, Columns.Count).End(xlToLeft).Column


Set prange = ws.Cells(1, 1).Resize(lastrow, lastcol)
Set ptCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
    SourceData:=prange)
    
Set pt = ptCache.CreatePivotTable(TableDestination:=ws.Cells(2, lastcol + 2), TableName:="PivotTable")
        
pt.ManualUpdate = True
 

Excel Facts

Whats the difference between CONCAT and CONCATENATE?
The newer CONCAT function can reference a range of cells. =CONCATENATE(A1,A2,A3,A4,A5) becomes =CONCAT(A1:A5)
Hi and Welcome to the Board,

That code worked for me and I wasn't able to replicate the error you describe.

What version of Excel are you using?

What happens when you watch the value of prange?
 
Upvote 0

Forum statistics

Threads
1,223,231
Messages
6,170,884
Members
452,364
Latest member
springate

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