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.
Related
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.
I am trying to write a macro that creates a pivot table on a new sheet based on data from a master spreadsheet. How can I adjust my code to do this?
I've gotten the code to work with static data but whenever the data is dynamic, the macro does not work. I believe the issue is with the first line starting with "srcData = ". The line below, which is commented out, works without any issues.
Option Explicit
Dim pivotSht As Worksheet
Dim dataSht As Worksheet
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim srcData As String
Dim pRange As Range
Dim lastR As Long
Dim lastC As Long
Public Sub buildPivot()
Set dataSht = Worksheets("OOB")
'Defines data range in "OOB" sheet
With dataSht
lastR = .Cells(.Rows.Count, "D").End(xlUp).Row
lastC = .Cells(4, .Columns.Count).End(xlToLeft).Column
Set pRange = .Range(.Cells(1, "D1"), Cells(lastR, lastC))
End With
Sheets("OOB").Activate
srcData = ActiveSheet.Name & "!" & pRange.Address(ReferenceStyle:=xlR1C1)
'srcData = ActiveSheet.Name & "!" & Range("D1:U714").Address(ReferenceStyle:=xlR1C1)
'Delete old "PivotTable" worksheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
'Create new sheet and name it "PivotTable"
Set pivotSht = Sheets.Add
ActiveSheet.Name = "PivotTable"
'Set location of pivot table
startPvt = pivotSht.Name & "!" & pivotSht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Define pivot cache
Set pCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=srcData)
'Creates pivot table from pivot cache
Set pTable = pCache.CreatePivotTable( _
tabledestination:=startPvt, _
TableName:="Open Order Book Table")
End Sub
The expected output is a pivot table using all data as the source, even with changing data.
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
I am trying to create a Pivot table on a newsheet using dynamic range, but getting an error that says:
Run time error: 13 Type Mismatch
Googled the error and as per my understanding, the code contains data type that is not matched correctly, but I am not able to figure out where is the error:
Using Excel 2016.
Sub EEE()
Dim PrevSheet As Worksheet
Set PrevSheet = ActiveSheet
Sheets.Add.Name = "Pivottable"
PrevSheet.Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=ActiveSheet.UsedRange, _
Version:=xlPivotTableVersion15).CreatePivotTable _
TableDestination:="Pivottable!R3C1", _
TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion15
Sheets("Pivottable").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Faculty")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("NPS")
.Orientation = xlColumnField
.Position = 1
End With
End Sub
Modified Code - Working
Sub EEE()
Dim rng As Range
Dim pc As PivotCache
Dim pt As PivotTable
Dim ws As Worksheet
Set rng = ActiveSheet.Range("A1").CurrentRegion
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabaseSourceData:=rng.Address)
Set ws = ActiveWorkbook.Worksheets.Add
ws.Name = "NewSheet"
Set pt = pc.CreatePivotTable(TableDestination:=Range("A3"),TableName:="pvttbl")
With pt
.PivotFields("Faculty").Orientation = xlRowField
ActiveSheet.PivotTables("pvttbl").AddDataField ActiveSheet.PivotTable "pvttbl").PivotFields("NPS"), "Count of NPS", xlCount
.PivotFields("NPS").Orientation = xlColumnField
End With
End Sub
You don't say what line is giving the error. But there's a couple of possible culprits.
The line SourceData:=ActiveSheet.UsedRange says "Hey, go make the PivotTable out of everything you find on the active sheet". Not a good idea. Use the exact range where the data is. Either select a cell where there block of data is and use the CurrentRegion e.g.
SourceData:= Activesheet.Range("A1").CurrentRegion
...or even better, turn that SourceData into an Excel Table aka ListObject earlier in the code, and reference that ListObject:
SourceData:= "Table1"
Your code will also fail if you try to run it more than once and you haven't deleted the sheet called "PivotTable" that it created last time.
Here's how I would code this up:
Option Explicit
Sub EEE()
Dim rng As Range
Dim pc As PivotCache
Dim pt As PivotTable
Dim pf As PivotField
Dim ws As Worksheet
Set rng = Range("A1").CurrentRegion '<- Change to the address of the top left cell in your data.
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rng.Address)
Set ws = ActiveWorkbook.Worksheets.Add
Set pt = pc.CreatePivotTable(TableDestination:=Range("A1"))
With pt
.PivotFields("Faculty").Orientation = xlRowField
.PivotFields("NPS").Orientation = xlColumnField
End With
End Sub
I am trying to create a pivot table on a new sheet. Additionally, I would like to create another call to create another different pivot table using the same data from the first data sheet.
having trouble with the macro below. I think it is a small error, but can't figure it out.
Sub Macro2()
Dim FinalRow As Long
Dim DataSheet As String
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim DataRng As Range
Dim TableDest As Range
Dim ws As Worksheet
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
'set data range for Pivot Table -- ' conversion of R1C1:R & FinalRow & C15
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 15))
Set ws = Worksheets.Add
ws.Name = "Travel Payment Data by Employee"
'set range for Pivot table placement -- Conversion of R1C1
Set TableDest = Sheets("Travel Payment Data by Employee").Cells(1, 1)
Set PvtCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, DataRng, xlPivotTableVersion15)
'check if "PivotTable4" Pivot Table already created (in past runs of this Macro)
Set PvtTbl = ActiveWorkbook.Sheets("Travel Payment Data by Employee").PivotTables("PivotTable4")
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
PvtTbl.AddDataField ActiveSheet.PivotTables( _
"PivotTable2").PivotFields("Dollar Amount"), "Sum of Dollar Amount", xlSum
End Sub
Consider the following adjustment with a subroutine calling a function, passing in new worksheet names for new identical pivot tables. If you do not intend identical pivots, adjust them in code conditionally by sheet name or copies of function. The main changes from your code are as follows:
ACTIVE SHEET: Remove the need to search ActiveSheet.Name as adding more worksheets will alter active sheets. Simply hard-code or pass as parameter the data source.
OBJECT CHECK: You need to check if Worksheet exits and PivotTable exists. For these, you will need to iterate through all current such objects and conditionally set worksheet, pivot table objects (see For...Next loops and If ... Is Nothing checks).
For PivotField, since Dollar Amounts will exist in Pivot Table data source but not necessarily display, iterating through all of them might not work like above. So conditionally add only if does not error out see On Resume Next handle.
VBA
Option Explicit
Public Sub RunPivots()
Call BuildPivot("Travel Payment Data by Employee")
Call BuildPivot("Other Worksheet")
Call BuildPivot("Still More Worksheet")
End Sub
Function BuildPivot(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
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = "DataSourceWorksheet"
' 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
' Add data field if does not exist
On Error Resume Next
PvtTbl.AddDataField PvtTbl.PivotFields("Dollar Amount"), "Sum of Dollar Amount", xlSum
Exit Function
ErrHandle:
MsgBox Err.Number & " - " & Err.Description, vbCritical, "RUNTIME ERROR"
Exit Function
End Function