Error 13 While creating a PivotTable - vba

I keep having the same error "13" "type incompatibility" while doing a pivot table.
Sub tracer()
Dim cache As PivotCache
Dim table As PivotTable
Dim prange As range
Dim lastrow As Long
Dim lastcol As Long
lastrow = data.Cells(data.Rows.count, "A").End(xlUp).Row
lastcol = 15
Set prange = data.Cells(1, 1).Resize(lastrow, lastcol)
graphe_clos.Select
Set cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=prange)
Set table = cache.CreatePivotTable(TableDestination:=graphe_clos.Cells(1, 1), TableName:="Terminator")
End Sub
Thank you for Help

The safer way to assign SourceData to your PivotCache is by using the following line
Set Cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pRange.Address(False, False, xlA1, xlExternal))
adding the fourth parameter xlExternal verifies that the range is also pulling the worksheet's name.
See more explanation inside the code's comments.
Modified Code
Sub tracer()
Dim Cache As PivotCache
Dim Table As PivotTable
Dim pRange As Range
Dim LastRow As Long
Dim LastCol As Long
' use With statement to shorten and fully qualify all your nested objects
With Data
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
LastCol = 15
' set the Range of the Pivot's data
Set pRange = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
' graphe_clos.Select '<-- you don't need to "Select" the sheet in order to create the Pivot-Table
End With
' set the Pivot Cache
Set Cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pRange.Address(False, False, xlA1, xlExternal))
' set the Pivot Table
Set Table = Cache.CreatePivotTable(TableDestination:=graphe_clos.Cells(1, 1), TableName:="Terminator")
End Sub
Regarding your latest question, modify:
With ActiveSheet.PivotTables("Terminator").PivotFields("Evt F")
With
With Table.PivotFields("Evt F")
since you already set your PivotTable object to Table.

Related

Invalid procedure call or argument in Pivot table creation

i have a hard time finding the solution for this error, i checked many posts but to no avail, it stays that there is a problem with this line
Set ptable = pCache.CreatePivotTable( _
TableDestination:=DestSheet.Cells(1, 1), _
TableName:="PivotTable1", _
DefaultVersion:=6)
so here is the code
Sub TestPivot()
Dim mySourceData As String
'Declare Variables
Dim SourceSheet As Worksheet
Dim DestSheet As Worksheet
'Declare Variales row and column
Dim FirstRow As Long
Dim LastRow As Long
Dim FirstCol As Long
Dim LastCol As Long
Dim ptable As PivotTable
Dim pCache As PivotCache
'Set/Define Source and Destination Variables
With ThisWorkbook
Set SourceSheet = Worksheets("W")
Set DestSheet = Worksheets("Pivot_W")
End With
'identify first row and first column of source data cell range
FirstRow = 2
FirstCol = 2
'Find last row and last column of source data cell range
'And obtain address of source data cell range
With Sheets("W").Range("A:N")
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
mySourceData = .Range(.Cells(FirstRow, FirstCol), .Cells(LastRow, LastCol)).Address(ReferenceStyle:=xlR1C1)
End With
'Insert Pivot Table
Set pCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SourceSheet.Name & "!" & mySourceData, Version:=6)
Set ptable = pCache.CreatePivotTable(TableDestination:=DestSheet.Cells(1, 1), TableName:="PivotTable1", DefaultVersion:=6)
If Not IsEmpty(ptable) Then
MsgBox "non vide"
End If
With DestSheet.PivotTables("PivotTable1").PivotFields("Magasin")
.Orientation = xlRowField
.Position = 1
End With
End Sub
I appreciate your help and thank you for reading my post.

Run-time error '5' Invalid procedure call or argument when defining Pivot Cache using VBA

I am finding this issue "Run-time error '5' Invalid procedure call or argument" when defining the PivotCache on my code. The Excel I am using is 2016 MSO (16.0.4266.1001) 32 bit. VBA 7.
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Sort Age of Case
LastRow = Cells(Rows.Count, 2).End(xlUp).Row
Range("M" & LastRow).Sort Key1:=Range("M3:M" & LastRow), _
Order1:=xlAscending, Header:=xlYes
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets.Add(After:=Worksheets(1)).Name = "US MASTER"
Application.DisplayAlerts = True
Set PSheet = Worksheets("US MASTER")
Set DSheet = Worksheets("US Master Macro")
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
'
'Pivot Table 1
'
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Range("B3"), TableName:="Total Backlog")
When creating a PivotCache, MSDN recommends using a String reference to specify the workbook, worksheet and cell range for SourceData, instead of passing a Range object.
Instead of using PRange (which you've forgotten to Set here), you can use R1C1 notation, like this answer suggests.
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
... SourceData:="'US Master Macro'!R1C1:R" & LastRow & "C" & LastCol
Just in case anyone is encountering a similar problem and the above answer does not solve, if you are using Slicers which are connected to various pivots (all of which come from the same data source) then the ChangePivotCache will not work unless you disconnect the pivots from the slicer first.
A few days of searching through questions/answers and finally came across the problem!

Application defined or object defined error vba pivot table

Respected Expert, I am trying to execute below VBA code for Define my data and refresh the Pivot Table but I Am getting defined or object defined error-1004. Please guide me where I am doing mistake on below.
Sub Pivot()
Dim shPivot As Worksheet
Dim shData As Worksheet
Dim lr As Long
Dim lc As Long
Dim rng As Range
Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")
lr = shPivot.Range("A" & Rows.Count).End(xlUp).Row
Set rng = shPivot.Range(Cells(1, 1), Cells(lr, 32))
With shData.PivotTables("PivotTable1").PivotCache
.SourceData = rng.Address(True, True, xlR1C1, True)
.Refresh
End With
End Sub
Try the code below:
Option Explicit
Sub Pivot()
Dim shPivot As Worksheet
Dim shData As Worksheet
Dim PT As PivotTable
Dim PTCache As PivotCache
Dim lr As Long
Dim lc As Long
Dim Rng As Range
Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")
With shPivot
lr = .Range("A" & .Rows.Count).End(xlUp).Row
Set Rng = .Range(.Cells(1, 1), .Cells(lr, 32))
End With
' set the Pivot Cache with the updated Data Source
' Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng)
' === Option 2 : set the Pivot Cache with the updated Data Source ===
Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=shPivot.Name & "!" & Rng.Address(True, True, xlR1C1, False))
' Set the Pivot Table to existing "PivotTable1" in "Data" sheet
Set PT = shData.PivotTables("PivotTable1")
With PT
.ChangePivotCache PTCache
.RefreshTable
End With
End Sub

Problems with obtaining last cell in VBA

I am trying to write a code to create a pivot table (as part of a much larger code) and I just can't get it to detect the source data. Unfortunately, each time the code will run the data will be of a different number of rows, so I want the code to automatically find the last cell with data in it.
I keep getting errors stating that an object is required or a variable is not defined. Despite going to the VBA error guide, I cant find what is wrong.
Can anyone see what the problem here is? Or even if there is a more efficient way to do it?
Sub CreatePivotTable()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As Range, LRow As Range, LCol As Range
'Determine the data range you want to pivot
Set LRow = Cells(Rows.Count, 1).End(xlUp).Row
Set LCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set SrcData = Worksheets("Raw Data").Range("A1:Cells(LRow,LCol)")
'Create a new worksheet
Sheets.Add.Name = "Pivot Table"
'Where do you want Pivot Table to start?
StartPvt = Worksheets("Occupancy").Range("A15")
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="Occupancy")
'Create the headings and row and column orientation
pvt.PivotFields("Precinct").Orientation = xlPageField
pvt.PivotFields("Number").Orientation.xlDataField.Function = xlCount
pvt.PivotFields("Captured Date").Orientation.xlColumnField.Position = 1
pvt.PivotFields("Captured Session").Orientation.xlColumnField.Position = 2
pvt.PivotFields("Session Location").Orientation.xlRowField.Position = 1
'Turn on Automatic updates/calculations --like screenupdating to speed up code
pvt.ManualUpdate = False
End Sub
Anything within quotes is a string and hence "A1:Cells(LRow,LCol)" becomes a string and doesn't take the address of the cells(LRow,LCol)
Change
Set SrcData = Worksheets("Raw Data").Range("A1:Cells(LRow,LCol)")
to
LastCol = Split(Cells(, LCol).Address, "$")(1)
Set SrcData = Worksheets("Raw Data").Range("A1:" & LastCol & LRow)
or to this
Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow,LCol).Address(False, False))
Also change
Dim LRow As Range, LCol As Range
Set LRow = Cells(Rows.Count, 1).End(xlUp).Row
Set LCol = Cells(1, Columns.Count).End(xlToLeft).Column
to
Dim LRow As Long, LCol As Long
LRow = Cells(Rows.Count, 1).End(xlUp).Row
LCol = Cells(1, Columns.Count).End(xlToLeft).Column
Use a table to store the data and give it a name. Then set the pivot source to the table name

Pivot table in same sheet VBA

I am trying to add a pivot table to the same worksheet I am on (the sheet is called holders (corp)) but am having trouble with that.
Sub PivotTable()
Sheets("Sheet2").Select
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim pf As PivotField
Dim StartPvt As String
Dim SrcData As String
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).row
'Determine the data range you want to pivot
SrcData = ActiveSheet.Name & "!" & Range(Cells(1, "A"), Cells(LastRow,"E")).Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set sht = Sheets("HOLDERS (CORP)")
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="HolderssPivotTable")
End Sub
I get a debug issue related to the call procedure at the very last 3 lines of code but am not sure why. Help would be much appreciated!
Excel VBA cannot accept R1C1 cell addresses in Range objects.
Change
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
To
StartPvt = sht.Range("A1").Address
Then change
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="HolderssPivotTable")
End Sub
To
Set pvt = pvtCache.CreatePivotTable(TableDestination:=sht.Range(StartPvt), _
TableName:="HolderssPivotTable")
Update - Full refactored code to ensure pivot table ends up on Holders (CORP) sheet.
Sub PivotTable()
Dim sht2 As Worksheet
Set sht2 = Sheets("Sheet2")
With sh2
Dim LastRow As Long
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Determine the data range you want to pivot
Dim SrcData As String
SrcData = .Name & "!" & .Range(.Cells(1, "A"), .Cells(LastRow, "E")).Address
End With
Dim sht As Worksheet
'Create a new worksheet
Set sht = Sheets("HOLDERS (CORP)")
'Where do you want Pivot Table to start?
Dim StartPvt As String
StartPvt = sht.Range("A1").Address
'Create Pivot Cache from Source Data
Dim pvtCache As PivotCache
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Dim pvt As PivotTable
Set pvt = pvtCache.CreatePivotTable(TableDestination:=sht.Range(StartPvt), TableName:="HolderssPivotTable")
End Sub