Application defined or object defined error vba pivot table - vba

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

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.

Error 13 While creating a PivotTable

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.

VBA - Loop Pivot Table Filtering Extract

I have the below code which applies a filter to a Pivot Table, then specific data is copied from the PivotTable and the filters are removed.. The issue is, this one block of code is used 22 times, the sub is waaaay too long.
Here is the code I have with only ONE of the blocks:
Option Explicit
Sub FilterPivotTable()
Dim rLastCell As Range
Dim PvtTbl As PivotTable
Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRow1 As Long
Set ws1 = ActiveWorkbook.Sheets("PivotTable")
Set ws2 = ActiveWorkbook.Sheets("Summary")
Dim rowCount As Long
LastRow1 = ws1.Cells(Rows.Count, 1)
'Microsoft Windows
Application.ScreenUpdating = False
ws1.PivotTables("P1").ManualUpdate = True
ws1.PivotTables("P1").PivotFields(" Vulnerability Name").ClearAllFilters
'---------------Block Starts Here---------------
ws1.PivotTables("P1").PivotFields(" Vulnerability Name").PivotFilters. _
Add Type:=xlCaptionContains, Value1:="Microsoft Windows"
ws1.PivotTables("P1").ManualUpdate = False
Application.ScreenUpdating = True
With ws1.PivotTables(1).TableRange1
Set rLastCell = .Cells(.Rows.Count, .Columns.Count)
Set PvtTbl = Worksheets("PivotTable").PivotTables("P1")
rLastCell.Copy
With ws2
.Cells(LastRow1 + 2, 3).PasteSpecial xlPasteValues
.Range("$B$2").Value = "Microsoft Windows"
rowCount = PvtTbl.DataBodyRange.Rows.Count
.Range("$D$2") = rowCount - 1
End With
End With
ws1.PivotTables("P1").PivotFields(" Vulnerability Name").ClearAllFilters
'---------------Block Ends Here---------------
End Sub
This block of code is repeated 22 times throughout this sub, each time only changing the vulnerability name i.e. Changing 'Microsoft Windows' to 'Adobe' and then changing the Cell Reference for where the data is to be copied to the Summary Sheet.
I am hoping to rather have one block of code that loops through the vulnerability names instead of having 22 different blocks of code performing the same function.
This is what the Pivot Table Structure looks like:
The filter is done under the rows block and done on Vulnerability Name
This is a bit of a punt in the dark I'm afraid
Option Explicit
Sub FilterPivotTable()
Dim rLastCell As Range
Dim PvtTbl As PivotTable
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = ActiveWorkbook.Sheets("PivotTable")
Set ws2 = ActiveWorkbook.Sheets("Summary")
Dim rowCount As Long
Dim LastRow1 As Long
Dim pvtField As PivotField
Set PvtTbl = ws1.PivotTables("P1")
Application.ScreenUpdating = False
Set pvtField = PvtTbl.PivotFields(" Vulnerability Name") 'extend etc as required
Dim myArr()
myArr = Array("Microsoft Windows", "Adobe Reader", "Other")
'PvtTbl.ManualUpdate = False
Dim i As Long
For i = LBound(myArr) To UBound(myArr)
pvtField.ClearAllFilters
pvtField.PivotFilters. _
Add Type:=xlCaptionContains, Value1:=myArr(i)
With ws1.PivotTables(1).TableRange1
Set rLastCell = .Cells(.Rows.count, .Columns.count) 'grand total?
End With
With ws2
LastRow1 = ws2.Cells(ws2.Rows.count, 3).End(xlUp).row
rLastCell.Copy
.Cells(LastRow1 + 1, 3).PasteSpecial xlPasteValues
.Cells(LastRow1 + 1, 2).Value = myArr(i)
rowCount = PvtTbl.DataBodyRange.Rows.count
.Cells(LastRow1 + 1, 4) = rowCount - 1
End With
Next i
Application.ScreenUpdating = True
'PvtTbl.ManualUpdate = False
End Sub

Error in Creating a Pivot table

I've been debugging this code for hours in creating a pivot table, but unfortunately, I'm not able to figure out the problem. It keeps on displaying, Object doesn't support this property or method.
Sub CreatePivotTable()
Dim sht, srcSheet As Worksheet, ccsheet As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim lrow As Long
Set srcSheet = ThisWorkbook.Sheets("Document Raw")
lrow = srcSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
Set ccsheet = ThisWorkbook.Sheets("Character Count")
SrcData = srcSheet & "!" & Range("A1:V"& lrow).Address(ReferenceStyle:=xlR1C1)' this is the line that errors
StartPvt = ccsheet & "!" & ccsheet.Range("A79").Address(ReferenceStyle:=xlR1C1)
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
End Sub
Any help? Thanks
Try the modified code below (i prefer to setup up the Range, later the PivotCache and PivotTable and this method):
Sub CreatePivotTable()
Dim srcSheet As Worksheet
Dim ccSheet As Worksheet
Dim pvtCache As PivotCache
Dim pvtTbl As PivotTable
Dim StartPvt As Range
Dim SrcData As Variant
Dim lrow As Long
Set srcSheet = ThisWorkbook.Sheets("Document Raw")
lrow = srcSheet.Cells(srcSheet.Rows.Count, 1).End(xlUp).Row
Set ccSheet = ThisWorkbook.Sheets("Character Count")
' make sure you have valid data from Column A to Column V
Set SrcData = srcSheet.Range("A1:V" & lrow)
Set StartPvt = ccSheet.Range("A79")
'Create Pivot table from Pivot Cache
Set pvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set pvtTbl = ccSheet.PivotTables("PivotTable1") ' check if "PivotTable1" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If pvtTbl Is Nothing Then
Set pvtTbl = ccSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=StartPvt, TableName:="PivotTable1")
Else
pvtTbl.ChangePivotCache pvtCache
pvtTbl.RefreshTable
End If
End Sub

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