Issue creating Pivot Table using Excel VBA - excel

I've been wanting to create a pivot table off of a sheet called "Data". I worked on the code at first and everything worked out, but for some reason I now get the following error:
Run-time error '440' Method 'Create" of object 'PivotCaches' failed
Here's my code:
Option Explicit
Dim wb As Workbook
Dim wsData As Worksheet, wsPT As Worksheet
Sub Create_Pivot_Table()
Dim LastRow As Long, LastColumn As Long
Dim DataRange As range
Dim PTCache As PivotCache
Dim PT As PivotTable
Set wb = ThisWorkbook
Set wsData = ThisWorkbook.Worksheets("Data")
Call Delete_PT_Sheet
With wsData
LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
LastColumn = .Cells(1, Columns.Count).End(xlToLeft).Column
Set DataRange = .range(.Cells(1, 1), .Cells(LastRow, LastColumn))
Set wsPT = wb.Worksheets.Add
wsPT.Name = "Pivot Table"
Set PTCache = wb.PivotCaches.Create(xlDatabase, DataRange)
Set PT = PTCache.CreatePivotTable(wsPT.range("B5"), "PIVOT")
With PT
'// Pivot Table Layout Settings
.RowAxisLayout xlTabularRow
.ColumnGrand = False
.RowGrand = False
.HasAutoFormat = False
'//Row Section (Layer 1)
With .PivotFields("Helper")
.Orientation = xlRowField
.Position = 1
.LayoutBlankLine = False
End With
'// Values Section
With .PivotFields("Quantity")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##;(#,##);-"
End With
End With
End With
wsPT.Cells.EntireColumn.AutoFit
'//Releasing object memories
Set PTCache = Nothing
Set wsPT = Nothing
Set DataRange = Nothing
Set wsData = Nothing
Set wb = Nothing
End Sub
Private Sub Delete_PT_Sheet()
On Error Resume Next
Application.DisplayAlerts = False
wb.Worksheets("Pivot Table").Delete
End Sub
Could someone review the code and help me to fix it?
Thanks in Advance!

Related

Change data source of several Pivot tables stored in the same worksheet

my problem is the following : I have a data source in sheets("Source") that I update time over time, so that the number of lines is increasing. I want to automatically update the Pivotables linked to this data source, in sheets("Overview") trhough a vba code. In Sheets ("Overview") there are 2 Pivot tables as well as plots.
Here is the code :
Sub UpdatePivotTableRange()
Dim Data_Sheet As Worksheet
Dim Pivot_Sheet As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName1 As String
Dim PivotName2 As String
Dim NewRange As String
Dim LastCol As Long
Dim lastRow As Long
'Set Pivot Table & Source Worksheet
Set Data_Sheet = ThisWorkbook.Worksheets("Source")
Set Pivot_Sheet = ThisWorkbook.Worksheets("Overview")
'Enter in Pivot Table Name
PivotName1 = "PivotTable1"
PivotName2 = "PivoTable2"
'Defining Staring Point & Dynamic Range
Data_Sheet.Activate
Set StartPoint = Data_Sheet.Range("A1")
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol))
NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
'Change Pivot Tables Data Source Range Address
Pivot_Sheet.PivotTables(PivotName1). _
ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
Pivot_Sheet.PivotTables(PivotName2). _
ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
'Ensure Pivot Table is Refreshed
Pivot_Sheet.PivotTables(PivotName1).RefreshTable
Pivot_Sheet.PivotTables(PivotName2).RefreshTable
'Complete Message
Pivot_Sheet.Activate
MsgBox "Your Pivot Table is now updated."
End Sub
I get the following errors :
either "Run-time error'5': Invalid procedure call or argument" or;
"Run-time error '1004': The Pivot Table field name is not valid".
Can you help please ?
Regards,
Leopold
`
Instead of the address of the cell, you can apply the range area directly.
Sub UpdatePivotTableRange()
Dim Data_Sheet As Worksheet
Dim Pivot_Sheet As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName1 As String
Dim PivotName2 As String
Dim NewRange As String
Dim LastCol As Long
Dim lastRow As Long
Dim Pv As PivotTable
Dim Wb As Workbook
Dim pvFD As PivotField
Set Wb = ThisWorkbook
'Set Pivot Table & Source Worksheet
Set Data_Sheet = ThisWorkbook.Worksheets("Source")
Set Pivot_Sheet = ThisWorkbook.Worksheets("Overview")
'Enter in Pivot Table Name
PivotName1 = "PivotTable1"
PivotName2 = "PivoTable2"
'Defining Staring Point & Dynamic Range
Data_Sheet.Activate
Set StartPoint = Data_Sheet.Range("A1")
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
With Data_Sheet
Set DataRange = .Range(StartPoint, .Cells(DownCell, LastCol))
'Set DataRange = StartPoint.CurrentRegion '<~~ same upper line
End With
'NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
'Change Pivot Tables Data Source Range Address
Set Pv = Pivot_Sheet.PivotTables(PivotName1)
With Pv
.ChangePivotCache Wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DataRange) '<~~ directly apply range object
.ClearTable '<~~ This is necessary because the item does not reflect well as it increases.
.RowAxisLayout xlCompactRow
.RefreshTable
End With
Set pvFD = Pv.PivotFields("id")
With pvFD
.Orientation = xlRowField
.Position = 1
End With
Set pvFD = Pv.PivotFields("name")
With pvFD
.Orientation = xlRowField
.Position = 2
End With
Set pvFD = Pv.PivotFields("id")
With pvFD
.Orientation = xlRowField
.Position = 1
End With
Set pvFD = Pv.CalculatedFields.Add("Mysum", Formula:="q1-q2")
With pvFD
.Orientation = xlDataField
.Position = 1
End With
Set Pv = Pivot_Sheet.PivotTables(PivotName2)
With Pv
.ChangePivotCache Wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DataRange) '<~~ directly apply range object
.ClearTable '<~~ This is necessary because the item does not reflect well as it increases.
.RowAxisLayout xlOutlineRow
.RefreshTable
End With
Set pvFD = Pv.PivotFields("id")
With pvFD
.Orientation = xlRowField
.Position = 1
End With
Set pvFD = Pv.PivotFields("name")
With pvFD
.Orientation = xlRowField
.Position = 2
End With
Set pvFD = Pv.PivotFields("id")
With pvFD
.Orientation = xlRowField
.Position = 1
End With
Set pvFD = Pv.CalculatedFields.Add("Mymutiply", Formula:="q1*q2")
With pvFD
.Orientation = xlDataField
.Position = 1
End With
Pivot_Sheet.Activate
MsgBox "Your Pivot Table is now updated."
End Sub
Data Sheet
Pivot Sheet

Excel Pivot table error 1004 when create the pivot

I am trying to create a pivot table, I found some code and I try to change it for my need, I take the error “1004” Application-defined or Object-defined error when I run the code, can anyone help?
Sub SalesNew()
Application.ScreenUpdating = False
Dim BACKORDER, Analysis As Workbook
Set BACKORDER = Workbooks("BACKORDER2019.xlsx")
Set Analysis = Workbooks("Analysis.xlsx")
Dim wsBACK As Worksheet
Set wsBACK = BACKORDER.Worksheets("Sheet1")
Dim RngBACKstart, RngBACKend, RngBACKnew As Range
Set RngBACKstart = wsBACK.Range("G4")
Set RngBACKend = wsBACK.Cells(wsBACK.Rows.Count, "G").End(xlUp)
Set RngBACKnew = Range(RngBACKstart, RngBACKend)
With RngBACKnew
.NumberFormat = "General"
.Value = .Value
End With
With BACKORDER
Sheets.Add(Before:=Worksheets(Worksheets.Count)).Name = "Pivot"
End With
Dim PSheet As Worksheet
Set PSheet = BACKORDER.Worksheets("Pivot")
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim FirstRow As Range
Dim LastCol As Range
Set FirstCell = wsBACK.Range("A3")
Set LastCell = wsBACK.Cells(wsBACK.Rows.Count, "H").End(xlUp)
Set PRange = Range(FirstCell, LastCell)
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), _
TableName:="SalesPivotTable")
Application.ScreenUpdating = False
End Sub

Copy Pivot table value to new sheet vba

I am trying to copy Pivot table values into a new sheet using VBA. I am getting a runtime error 5. Here is my code
Sub test()
Dim shtTarget As Worksheet, pvtSht As Worksheet
Dim pc As PivotCache
Dim pt As PivotTable
Dim field As PivotField
Dim rngSource As Range
Dim wb As Workbook: Set wb = ThisWorkbook
With wb
Set rngSource = .Sheets(2).Range("A5").CurrentRegion
Set shtTarget = .Sheets.Add(After:=.Sheets(.Sheets.Count))
Set pc = .PivotCaches.Create(xlDatabase, rngSource.Address(False, False, xlA1, xlExternal))
Set pt = pc.CreatePivotTable(shtTarget.Range("A1"), "PivotTable3", , xlPivotTableVersion14)
End With
With pt.PivotFields("Concatenate")
.Orientation = xlRowField
.Position = 1
End With
pt.AddDataField pt.PivotFields("SCREEN_ENTRY_VALUE"), "Sum of SCREEN_ENTRY_VALUE", xlSum
With wb
Set pvtSht = .Sheets.Add(After:=.Sheets(.Sheets.Count))
pvtSht.Name = "Sum of Element Entries"
pt.TableRange2.Copy
pvtSht.Range("A1").PasteSpecial xlPasteValues
End With
End Sub
My pivot table is in a range of A5:I266. The code errors out on Set pt = pc.CreatePivotTable...
Replace:
Set pt = pc.CreatePivotTable(shtTarget.Range("A1"), "PivotTable3", , xlPivotTableVersion14)
with:
Set pt = pc.CreatePivotTable(shtTarget.Range("A1"), "PivotTable3")

VBA Excel file size containing multiple pivot tables is huge

I am automating the process of creating pivot tables in excel. The problem I have is that the pivot tables I create using my macro is way larger than the ones I create manually. Both of the pivot tables look identical but there is a great difference in file size.
As seen in the image above, the one created by my macro is about 6 times larger! I suspect that it is the way I cache for the data when creating my pivot tables. So, here is the general code I use to create my pivot tables.
Sub pivottable1()
Dim PSheet As Worksheet, DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PField As PivotField
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
Dim PvtTable As PivotTable
Dim SheetName As String
Dim PTName As String
SheetName = "MySheetName1"
PTName = "PivotTable1"
On Error Resume Next
Application.DisplayAlerts = False
Worksheets(SheetName).Delete
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = SheetName
Application.DisplayAlerts = True
Set PSheet = Worksheets(SheetName)
Set DSheet = Worksheets(1)
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(4, 1), _
TABLENAME:=PTName)
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TABLENAME:=PTName)
Sheets(SheetName).Select
Set PvtTable = ActiveSheet.PivotTables(PTName)
'Rows
With PvtTable.PivotFields("TypeCol")
.Orientation = xlRowField
.Position = 1
End With
With PvtTable.PivotFields("NameCol")
.Orientation = xlRowField
.Position = 2
End With
'Columns
With PvtTable.PivotFields("CategoryCol")
.Orientation = xlColumnField
.Position = 1
End With
'Values
PvtTable.AddDataField PvtTable.PivotFields("Values1"), "Value Balance", xlSum
PvtTable.AddDataField PvtTable.PivotFields("Values2"), "Value 2 Count", xlCount
With PvtTable
.PivotFields("TypeCol").ShowDetail = False
.TableRange1.Font.Size = 10
.ColumnRange.HorizontalAlignment = xlCenter
.ColumnRange.VerticalAlignment = xlTop
.ColumnRange.WrapText = True
.ColumnRange.Columns.AutoFit
.ColumnRange.EntireRow.AutoFit
.RowAxisLayout xlTabularRow
.ShowTableStyleRowStripes = True
.PivotFields("TypeCol").AutoSort xlDescending, "Value Balance" 'Sort descdending order
.PivotFields("NameCol").AutoSort xlDescending, "Value Balance"
End With
'Change Data field (Values) number format to have thousand seperator and 0 decimal places.
For Each PField In PvtTable.DataFields
PField.NumberFormat = "#,##0"
Next PField
End Sub
This is how I create 6 different pivot tables which all uses the same source of data which is located in the same workbook and is in the first worksheet of that workbook. So, for example my second pivot table macro code would look something like this.
Sub pivottable2()
Dim PSheet As Worksheet, DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PField As PivotField
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
Dim PvtTable As PivotTable
Dim SheetName As String
Dim PTName As String
SheetName = "MySheetName2"
PTName = "PivotTable2"
On Error Resume Next
Application.DisplayAlerts = False
Worksheets(SheetName).Delete
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = SheetName
Application.DisplayAlerts = True
Set PSheet = Worksheets(SheetName)
Set DSheet = Worksheets(1)
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(4, 1), _
TABLENAME:=PTName)
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TABLENAME:=PTName)
Sheets(SheetName).Select
Set PvtTable = ActiveSheet.PivotTables(PTName)
'Rows
With PvtTable.PivotFields("ManagerCol")
.Orientation = xlRowField
.Position = 1
End With
With PvtTable.PivotFields("IDCol")
.Orientation = xlRowField
.Position = 2
End With
'Columns
With PvtTable.PivotFields("CategoryCol")
.Orientation = xlColumnField
.Position = 1
End With
'Values
PvtTable.AddDataField PvtTable.PivotFields("Values1"), "Value Balance", xlSum
End Sub
All that I change would be the macro name, the worksheet name, the pivot table name and the input rows/columns/data values for the pivot table.
What I hope to accomplish is to reduce the file size of my macro created pivot tables, to something similar of the ones I create manually.
If there is anything extra that you guys would like to know, please comment. I will make an edit with the question and add the details respectively.
You can use the same pivotcache for multiple pivottables (assuming they're based on the same source data).
Untested:
'creates and returns a shared pivotcache object
Function GetPivotCache() As PivotCache
Static pc As PivotCache 'static variables retain their value between calls
Dim pRange As Range
If pc Is Nothing Then 'create if not yet created
Set prRange = Worksheets(1).Range("A1").CurrentRegion
Set pc = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=pRange)
End If
Set GetPivotCache = pc
End Function
Sub pivottable1()
'...
'...
Set PSheet = Worksheets(SheetName)
Set PCache = GetPivotCache() '<<< will be created if needed
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:=PTName)
'...
'...
End Sub
I've seen this behavior before. By the very nature of creating Pivots, your WB will bloat up, just as you are seeing now. In the past I have used VBA to create the Pivots, exactly like you are doing, and then right at the end, run a small script to do copy all, and paste special values. That will eliminate most, and perhaps all, of the bloat. Also, instead of saving your WB as XLSX, try XLSB, which will be around 4x smaller than XLSX and open/close around 4x faster than XLSX. I'm wondering why you are even using XLSX, because you can't save Macros in that format. Or, maybe you have a template WB that does all the work, and you simply save new reports as XLSX. Anyway, consider using the XLSB format from now on.

How to create pivot table using vba

I am newbie in vba and am trying to create a PivotTable using VBA with excel.
I would like to creat like as below image as input sheet.
I am trying to add row labels of region, month, number, status and values are value1, value2 and total here I am able to set range for pivot, while executing it creates "pivottable" sheet only. not generate any pivot table for sheet1.
My Code:
Option Explicit
Public Sub Input_File__1()
ThisWorkbook.Sheets(1).TextBox1.Text = Application.GetOpenFilename()
End Sub
'======================================================================
Public Sub Output_File_1()
Dim get_fldr, item As String
Dim fldr As FileDialog
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.AllowMultiSelect = False
If .Show <> -1 Then GoTo nextcode:
item = .SelectedItems(1)
If Right(item, 1) <> "\" Then
item = item & "\"
End If
End With
nextcode:
get_fldr = item
Set fldr = Nothing
ThisWorkbook.Worksheets(1).TextBox2.Text = get_fldr
End Sub
'======================================================================
Public Sub Process_start()
Dim Raw_Data_1, Output As String
Dim Raw_data, Start_Time As String
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
Start_Time = Time()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Raw_Data_1 = ThisWorkbook.Sheets(1).TextBox1.Text
Output = ThisWorkbook.Sheets(1).TextBox2.Text
Workbooks.Open Raw_Data_1: Set Raw_data = ActiveWorkbook
Raw_data.Sheets("Sheet1").Activate
On Error Resume Next
'Worksheets("Sheet1").Delete
Sheets.Add before:=ActiveSheet
ActiveSheet.Name = "Pivottable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Pivottable")
Set DSheet = Worksheets("Sheet1")
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).coloumn
Set PRange = DSheet.Range("A1").CurrentRegion
Set PCache = ActiveWorkbook.PivotCaches.Create_(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="PRIMEPivotTable")
With PTable.PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
This needs some tidying up but should get you started.
Note the use of Option Explicit so variables have to be declared.
Columns names are as per your supplied workbook.
Option Explicit
Sub test()
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim PRange As Range
Dim PCache As PivotCache
Dim PTable As PivotTable
Sheets.Add
ActiveSheet.Name = "Pivottable"
Set PSheet = Worksheets("Pivottable")
Set DSheet = Worksheets("Sheet1")
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Range("A1").CurrentRegion
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="PRIMEPivotTable")
With PTable.PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
With PTable.PivotFields("Channel")
.Orientation = xlRowField
.Position = 2
End With
With PTable.PivotFields("AW code")
.Orientation = xlRowField
.Position = 3
End With
PTable.AddDataField PSheet.PivotTables _
("PRIMEPivotTable").PivotFields("Bk"), "Sum of Bk", xlSum
PTable.AddDataField PSheet.PivotTables _
("PRIMEPivotTable").PivotFields("DY"), "Sum of DY", xlSum
PTable.AddDataField PSheet.PivotTables _
("PRIMEPivotTable").PivotFields("TOTal"), "Sum of TOTal", xlSum
End Sub
The code in my answer below is a little long, but it should deliver you the result you are seeking for.
First, to be on the safe side, first check if "Pivottable" sheet already exists in Raw_data workbook object (no need to create it again).
Second, the code is divided in the middle to 2 sections:
If the MACRO was ran before (this is the 2+ times you are running it), then "PRIMEPivotTable" Pivot-Table is already created, and there’s no need to create it again, or to set-up the Pivot-Table’s fields.
All you need to do is refresh the PivotTable with the updated PivotCache (with updated Pivot-Cache’s source range).
If this is the first time running this MACRO, then you need to set-up the PivotTable and all necessary PivotFields.
Detaile explanation of every step inide the code's comments.
Code
Option Explicit
Sub AutoPivot()
Dim Raw_data As Workbook
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PTable As PivotTable
Dim PCache As PivotCache
Dim PRange As Range
Dim LastRow As Long, LastCol As Long
Dim Raw_Data_1 As String, Output As String, Start_Time As String
Start_Time = Time()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Raw_Data_1 = ThisWorkbook.Sheets(1).TextBox1.Text
Output = ThisWorkbook.Sheets(1).TextBox2.Text
' set the WorkBook object
Set Raw_data = Workbooks.Open(Raw_Data_1)
Set DSheet = Raw_data.Worksheets("Sheet1")
' first check if "Pivottable" sheet exits (from previous MACRO runs)
On Error Resume Next
Set PSheet = Raw_data.Sheets("Pivottable")
On Error GoTo 0
If PSheet Is Nothing Then '
Set PSheet = Raw_data.Sheets.Add(before:=Raw_data.ActiveSheet) ' create a new worksheet and assign the worksheet object
PSheet.Name = "Pivottable"
Else ' "Pivottable" already exists
' do nothing , or something else you might want
End If
With DSheet
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
' set the Pivot-Cache Source Range with the values found for LastRow and LastCol
Set PRange = .Range("A1", .Cells(LastRow, LastCol))
End With
' set a new/updated Pivot Cache object
Set PCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=PRange.Address(True, True, xlA1, xlExternal))
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PTable = PSheet.PivotTables("PRIMEPivotTable") ' check if "PRIMEPivotTable" Pivot-Table already created (in past runs of this Macro)
On Error GoTo 0
If PTable Is Nothing Then ' Pivot-Table still doesn't exist, need to create it
' create a new Pivot-Table in "Pivottable" sheet
Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Range("A1"), TableName:="PRIMEPivotTable")
With PTable
' add the row fields
With .PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("month")
.Orientation = xlRowField
.Position = 2
End With
With .PivotFields("number")
.Orientation = xlRowField
.Position = 3
End With
With .PivotFields("Status")
.Orientation = xlRowField
.Position = 4
End With
' add the 3 value fields (as Sum of..)
.AddDataField .PivotFields("value1"), "Sum of value1", xlSum
.AddDataField .PivotFields("value2"), "Sum of value2", xlSum
.AddDataField .PivotFields("TOTal"), "Sum of TOTal", xlSum
End With
Else ' Pivot-Table "PRIMEPivotTable" already exists >> just update the Pivot-Table with updated Pivot-Cache (update Source Range)
' just refresh the Pivot cache with the updated Range
PTable.ChangePivotCache PCache
PTable.RefreshTable
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Resources