How to create pivot table using vba - excel

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

Related

Issue creating Pivot Table using Excel VBA

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!

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

VBA to copy Pivot Table Data into another sheet + change headers

I am trying to copy the data in plain format into another sheet, and do further transformation on it.
While I can create the Pivot Table, but whenever I try to copy it into another sheet, the new sheet is empty. Wondering if any experts can point me to where I'm doing this wrongly. Below are my codes for reference:
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim CSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'*****************************************************
' Declare variables
'*****************************************************
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Pivot_Table").Delete
Worksheets("Cleaned_Data").Delete
Worksheets("RAW_DATA").Activate
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Pivot_Table"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Pivot_Table")
Set DSheet = Worksheets("RAW_DATA")
'*****************************************************
' Define data range for pivot
'*****************************************************
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PivotRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'*****************************************************
' Create pivot cache
'*****************************************************
Set PivotCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PivotRange).CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="UserPivotTable")
'*****************************************************
' Insert blank pivot
'*****************************************************
Set PTable = PivotCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="UserPivotTable")
'*****************************************************
' Insert row fields
'*****************************************************
With ActiveSheet.PivotTables("UserPivotTable").PivotFields("userid")
.Orientation = xlRowField
.Position = 1
End With
'*****************************************************
' Insert data field
'*****************************************************
With ActiveSheet.PivotTables("UserPivotTable").PivotFields("QTY")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
'.NumberFormat = "#,##0"
'.Name = "Revenue "
End With
'*****************************************************
' Copy data into another sheet for cleaning
'*****************************************************
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Cleaned_Data"
Application.DisplayAlerts = True
Set CSheet = Worksheets("Cleaned_Data")
PTable.TableRange2.Copy
CSheet.Range("A1").PasteSpecial xlPasteValues
Also with that, how should I customize the headers once I have copied the data into the new sheet?
For consistency, add the missing variables to your dim section:
Dim pivotRange As Range
Dim pivotCache As pivotCache
And change your second last line, the copy line to:
PSheet.PivotTables("UserPivotTable").TableRange2.Copy
If you debug your code, the you'll see, that PivotCache is Nothing.
Your code row Set PivotCache = is just too long.
As you only need the reference to a new PivotCache there, use this:
Set PivotCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PivotRange)
Further hints:
You should not use VBA-internal names as variable names.
See this concerning further formatting.

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.

Multiple Function Call - Public Sub

I am trying to get my Public Sub to make a call against two functions, each creating different pivot tables off of the same data sheet. I know that both of my functions work independently, but I keep getting an "application defined or object defined error" when I combine them in to a single sub.
The macro below does execute the first function and creates the intended pivot table. It just stops when it gets to the second function and provides me with the application or object defined error mentioned above. I have independently defined each function so I am not sure why I am getting an issue.
Option Explicit
Public Sub RunPivots()
Call BuildPivot1("Travel Payment Data by Employee")
Call BuildPivot2("Travel Payment Data by Acct Dim")
End Sub
Function BuildPivot1(paramSheet As String)
On Error GoTo ErrHandle
Dim FinalRow As Long
Dim DataSheet As String
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim PvtFld As PivotField
Dim DataRng As Range
Dim TableDest As Range
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
If ws.Name Like "*SQL" & "*" Then
'~~> This check is required to ensure that you don't get an error
'~~> if there is only one sheet left and it matches the delete criteria
If ThisWorkbook.Sheets.Count = 1 Then
MsgBox "There is only one sheet left and you cannot delete it"
Else
'~~> This is required to supress the dialog box which excel shows
'~~> When you delete a sheet. Remove it if you want to see the
'~~~> Dialog Box
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
End If
Next
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = "Export Worksheet"
' set data range for Pivot Table
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 15))
' check if worksheet exists
Dim currws As Worksheet
For Each currws In ActiveWorkbook.Worksheets
If currws.Name = paramSheet Then
Set ws = Worksheets(paramSheet)
Exit For
End If
Next currws
' create new worksheet if does not exist
If ws Is Nothing Then
Set ws = Worksheets.Add
ws.Name = paramSheet
End If
' set range for Pivot table placement
Set TableDest = Sheets(paramSheet).Cells(1, 1)
' create pivot cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=DataRng, _
Version:=xlPivotTableVersion15)
'check if "PivotTable4" Pivot Table exists
Dim currpvt As PivotTable
For Each currpvt In ws.PivotTables
If currpvt.Name = "PivotTable4" Then
Set PvtTbl = ws.PivotTables("PivotTable4")
Exit For
End If
Next currpvt
' create new pivot table if does not exist
If PvtTbl Is Nothing Then
Set PvtTbl = PvtCache.CreatePivotTable( _
TableDestination:=TableDest, _
TableName:="PivotTable4")
End If
With PvtTbl.PivotFields("Security Org")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Fiscal Month")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Budget Org")
.Orientation = xlRowField
.Position = 3
End With
With PvtTbl.PivotFields("Vendor Name")
.Orientation = xlRowField
.Position = 4
End With
With PvtTbl.PivotFields("Fiscal Year")
.Orientation = xlRowField
.Position = 5
End With
With PvtTbl.PivotFields("Fiscal Year")
.Orientation = xlColumnField
.Position = 1
End With
Range("B:E").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.NumberFormat = "$#,##0.00"
Range("B1").Select
PvtTbl.CompactLayoutColumnHeader = _
"Fiscal Year"
Range("A2").Select
PvtTbl.CompactLayoutRowHeader = _
"Security Org and Vendor"
Range("G8").Select
' Add data field if does not exist
On Error Resume Next
PvtTbl.AddDataField PvtTbl.PivotFields("Dollar Amount"), "Sum of Dollar Amount", xlSum
PvtTbl.PivotFields("Budget Org").ShowDetail = _
False
Exit Function
ErrHandle:
MsgBox Err.Number & " - " & Err.Description, vbCritical, "RUNTIME ERROR"
Exit Function
End Function
Function BuildPivot2(paramSheet As String)
On Error GoTo ErrHandle
Dim FinalRow As Long
Dim DataSheet As String
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim PvtFld As PivotField
Dim DataRng As Range
Dim TableDest As Range
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
If ws.Name Like "*SQL" & "*" Then
'~~> This check is required to ensure that you don't get an error
'~~> if there is only one sheet left and it matches the delete criteria
If ThisWorkbook.Sheets.Count = 1 Then
MsgBox "There is only one sheet left and you cannot delete it"
Else
'~~> This is required to supress the dialog box which excel shows
'~~> When you delete a sheet. Remove it if you want to see the
'~~~> Dialog Box
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
End If
Next
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = "Export Worksheet"
' set data range for Pivot Table
DataSheet = "Export Worksheet"
' set data range for Pivot Table
With Sheets(DataSheet)
Set DataRng = .Range(Cells(1, 1), .Cells(FinalRow, 15))
End With
' check if worksheet exists
Dim currws As Worksheet
For Each currws In ActiveWorkbook.Worksheets
If currws.Name = paramSheet Then
Set ws = Worksheets(paramSheet)
Exit For
End If
Next currws
' create new worksheet if does not exist
If ws Is Nothing Then
Set ws = Worksheets.Add
ws.Name = paramSheet
End If
' set range for Pivot table placement
Set TableDest = Sheets(paramSheet).Cells(1, 1)
' create pivot cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=DataRng, _
Version:=xlPivotTableVersion15)
'check if "PivotTable4" Pivot Table exists
Dim currpvt As PivotTable
For Each currpvt In ws.PivotTables
If currpvt.Name = "PivotTable4" Then
Set PvtTbl = ws.PivotTables("PivotTable4")
Exit For
End If
Next currpvt
' create new pivot table if does not exist
If PvtTbl Is Nothing Then
Set PvtTbl = PvtCache.CreatePivotTable( _
TableDestination:=TableDest, _
TableName:="PivotTable4")
End If
With PvtTbl.PivotFields("Fiscal Year")
.Orientation = xlColumnField
.Position = 1
End With
With PvtTbl.PivotFields("Fund")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Budget Org")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Cost Org")
.Orientation = xlRowField
.Position = 3
End With
Range("B:E").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.NumberFormat = "$#,##0.00"
Range("B1").Select
PvtTbl.CompactLayoutColumnHeader = _
"Fiscal Year"
Range("A2").Select
PvtTbl.CompactLayoutRowHeader = _
"Security Org and Vendor"
Range("G8").Select
' Add data field if does not exist
On Error Resume Next
PvtTbl.AddDataField PvtTbl.PivotFields("Dollar Amount"), "Sum of Dollar Amount", xlSum
PvtTbl.PivotFields("Budget Org").ShowDetail = _
False
Exit Function
ErrHandle:
MsgBox Err.Number & " - " & Err.Description, vbCritical, "RUNTIME ERROR"
Exit Function
End Function
You need to make sure all of your Cells() and Range() calls are qualified with a worksheet object. For example:
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 15))
will fail if the DataSheet worksheet is not the activesheet.
Fix like this:
With Sheets(DataSheet)
Set DataRng = .Range(.Cells(1, 1), .Cells(FinalRow, 15))
End With

Resources