I have been trying for hours now to create a pivot table from VBA. I've tried various codes but i keep getting errors. The following code does not create a pivot table it only creates a new sheet. I have a sheet called "Base" where all my data is. It has 18288 rows and 13 columns with data. Can anyone help me with why the code isn't working for me
Sub pivottable()
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
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Base")
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(2, 2), _
TableName:="PivotTable")
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="PivotTable")
Sheets("PivotTable").Select
With ActiveSheet.PivotTables("PivotTable").PivotFields("FACULTY_ID")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("PROGRAM_TYPE_NAME")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable").AddDataField ActiveSheet.PivotTables( _
"PivotTable").PivotFields("PROGRAM_TYPE_LETTER"), "Sum of amount", xlSum
End Sub
This might work for you:
Sub pivottable()
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
Dim new_sheet As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Application.DisplayAlerts = True
On Error GoTo 0
new_sheet_name = "PivotTable"
pivot_table_name = "pivot_name_here"
Set new_sheet = Sheets.Add(Before:=ActiveSheet)
With new_sheet
.Name = new_sheet_name
End With
Set PSheet = new_sheet
Set DSheet = Worksheets("Base")
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.Address(, , xlR1C1))
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1).Address(, , xlR1C1), TableName:=pivot_table_name)
With PTable.PivotFields("FACULTY_ID")
.Orientation = xlRowField
.Position = 1
End With
With PTable.PivotFields("PROGRAM_TYPE_NAME")
.Orientation = xlRowField
.Position = 2
End With
With PTable
.AddDataField ActiveSheet.PivotTables( _
"PivotTable").PivotFields("PROGRAM_TYPE_LETTER"), "Sum of amount", xlSum
End With
End Sub
Looks like this link is cold, but in case someone else wants to do this, here's code I adapted from other answers (StackOverflow and elsewhere) to create several Pivot Tables. This code receives a Global Variable from above that is an array with 7 salesman's names. The code:
Finds the range of the data on each "salesman's" sheet.
Creates a Pivot Table Cache with the salesman's name (this was the key to getting it to work).
Creates a Pivot table with the salesman's name.
Labels and sorts the Pivot Table.
Moves on to the next Sheet.
Sub Pivot_Maker() 'adapted from the internet. I added the arrays tho - AAI
'as of 11/26/2019
Dim FinalRow As Long
Dim DataSheet As String
Dim PvtCache As PivotCache
Dim PvtTbl(7) As PivotTable
Dim DataRng As Range
Dim TableDest As Range
i = 0
Do While i < NumSalesPeeps
Sheets(Salesman(i)).Select
Range("A1").Select
If IsEmpty(Range("A30")) Then GoTo No_Data
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
PvtTblName = ActiveSheet.Name & "pvt"
' set data range for Pivot Table
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 10)) ' conversion of R1C1:R & FinalRow & C8
' set range for Pivot table placement
Set TableDest = Sheets(DataSheet).Cells(1, 12) ' conversion of R1C9
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, DataRng)
' this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl(i) = ActiveWorkbook.Sheets(DataSheet).PivotTables(PvtTblName) ' check if PvtTblName Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl(i) Is Nothing Then ' PvtTblName doesn't exist >> create it
' create a new Pivot Table in PvtTblName sheet
Set PvtTbl(i) = ActiveWorkbook.Sheets(DataSheet).PivotTables.Add(PivotCache:=PvtCache, TableDestination:=TableDest, TableName:=PvtTblName)
With PvtTbl(i).PivotFields("Account")
.Orientation = xlColumnField
.Position = 1
End With
With PvtTbl(i).PivotFields("Name")
.Orientation = xlRowField
.Position = 1
End With
PvtTbl(i).AddDataField ActiveSheet.PivotTables( _
PvtTblName).PivotFields("Amount"), "Sum of Amount", xlSum
Else
' just refresh the Pivot cache with the updated Range
PvtTbl(i).ChangePivotCache PvtCache
PvtTbl(i).RefreshTable
End If
With ActiveSheet.PivotTables(PvtTblName).PivotFields("Sum of Amount")
.NumberFormat = "$#,##0"
End With
No_Data:
i = i + 1
Loop
End Sub
Related
I am trying to run vba on Pivot Tables since I need to update like 50+ tables for my report which would only save time if I can do this using vba.
Using vba, I can copy results from pivot tables directly into cells of another sheet of the same workbook. I got stuck trying to add filters.
I was able to run the first part where I got my summary info and now I am trying to add a "Revised Territory" filter and I want to filter for "SE" then it just didn't do anything.
I used F8 to check and it looks like it just goes through without any error but did not add any filter and so I got the same info as my summary data.
My Code
Sub InsertPivotTable()
''''''''''''''''''
'''Pivot Set Up'''
''''''''''''''''''
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim SSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("PIF Data")
Set SSheet = Worksheets("Summary")
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = 76
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'''''''''
'Summary'
'''''''''
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(3, 1), _
TableName:="NB Summary")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="NB Summary")
Dim Pvt As PivotTable
Set Pvt = Worksheets("PivotTable").PivotTables("NB Summary")
'Add fields to rows & values, re-name title of value
With Pvt
.PivotFields("Policy Form").Orientation = xlColumnField
.PivotFields("Phone/Email").Orientation = xlRowField
.AddDataField .PivotFields("Policy Number"), "Count of Policy Number", xlCount
End With
PSheet.Range("B5:B6").Copy
SSheet.Range("E6").PasteSpecial Paste:=xlPasteValues
PSheet.Range("C5:C6").Copy
SSheet.Range("G6").PasteSpecial Paste:=xlPasteValues
''''
'SE'
''''
With Pvt
.ClearAllFilters
.PivotFields("Revised Territory").PivotFilter.Add Type:=xlCaptionContains, Value1:="SE"
End With
PSheet.Range("B5:B6").Copy
SSheet.Range("E12").PasteSpecial Paste:=xlPasteValues
PSheet.Range("C5:C6").Copy
SSheet.Range("G12").PasteSpecial Paste:=xlPasteValues
'Delete PivotTable Sheet
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Application.DisplayAlerts = True
End Sub
Try the code below, detailed explanations in the code's comments.
Modified Code
Option Explicit
Sub InsertPivotTable()
''''''''''''''''''
'''Pivot Set Up'''
''''''''''''''''''
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim SSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PFld As PivotField
Dim PItm As PivotItem
Dim PRange As Range
Dim LastRow As Long, LastCol As Long
' --- Check if there's already a sheet named "PivotTable" ---
On Error Resume Next
Set PSheet = ThisWorkbook.Sheets("PivotTable")
On Error GoTo 0
If PSheet Is Nothing Then ' there's no sheet named "PivotTable" >> create one
Set PSheet = ThisWorkbook.Sheets.Add(Before:=ActiveSheet)
PSheet.Name = "PivotTable"
End If
Application.DisplayAlerts = True
Set DSheet = Worksheets("PIF Data")
Set SSheet = Worksheets("Summary")
'Define Data Range
With DSheet
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LastCol = 76 ' <-- you have 76 Colkumns of Data ??!
Set PRange = .Cells(1, 1).Resize(LastRow, LastCol)
End With
'''''''''
'Summary'
'''''''''
' Set Pivot Cache object
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange.Address(False, False, xlA1, xlExternal))
' create a new Pivot Table in "PivotTable" sheet, start from Cell A1
Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Range("A1"), TableName:="NB Summary")
' Add fields to rows & values, re-name title of value
With PTable
.PivotFields("Policy Form").Orientation = xlColumnField
.PivotFields("Phone/Email").Orientation = xlRowField
.AddDataField .PivotFields("Policy Number"), "Count of Policy Number", xlCount
End With
PSheet.Range("B5:B6").Copy
SSheet.Range("E6").PasteSpecial Paste:=xlPasteValues
PSheet.Range("C5:C6").Copy
SSheet.Range("G6").PasteSpecial Paste:=xlPasteValues
''''
'SE'
''''
' ===== Filter PivotField "Revised Territory" section according to "SE" =====
With PTable
.ClearAllFilters
' set PivotField "Revised Territory"
Set PFld = .PivotFields("Revised Territory")
With PFld
.Orientation = xlPageField
.Position = 1
' loop through PivotField "Revised Territory" pivot-items
For Each PItm In .PivotItems
If PItm.Caption = "SE" Then
PItm.Visible = True
Else
PItm.Visible = False
End If
Next PItm
End With
End With
PSheet.Range("B5:B6").Copy
SSheet.Range("E12").PasteSpecial Paste:=xlPasteValues
PSheet.Range("C5:C6").Copy
SSheet.Range("G12").PasteSpecial Paste:=xlPasteValues
'Delete PivotTable Sheet
Application.DisplayAlerts = False
PSheet.Delete
Application.DisplayAlerts = True
End Sub
The VBA code I have below is trying to create a Pivot Table based on data in "Sheet2", adding a new sheet "Pivot Table" and creating a Pivot Table on this sheet.
However the code is executing without error, just no table appears on the new sheet "Pivot Table" and I cannot see why.
Also the data on Sheet2 for the PT currently begins in column B, not sure if this is having an effect.
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow1 As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Sheet2")
'Define Data Range
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)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="MilestonePivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="MilestonePivotTable")
'Insert Row Fields
With ActiveSheet.PivotTables("MilestonePivotTable").PivotFields("Resource Name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("MilestonePivotTable").PivotFields("Deliverable")
.Orientation = xlRowField
.Position = 2
End With
'Insert Column Fields
With ActiveSheet.PivotTables("MilestonePivotTable").PivotFields("Milestone Date")
.Orientation = xlColumnField
.Position = 1
End With
Only semi-tested (due to only having dummy data) but I believe the following will fix all your errors:
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
'LastRow was not declared
Dim LastRow As Long
'LastRow1 is not used
'Dim LastRow1 As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
'Switch off error "masking" once you don't need it
On Error GoTo 0
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Sheet2")
'Define Data Range
'a) Base last row on column B if you don't have data in column A
'b) Use "DSheet.Rows.Count" and "DSheet.Columns.Count" - although not strictly
' necessary in this situation, it is a good practice to get into
LastRow = DSheet.Cells(DSheet.Rows.Count, "B").End(xlUp).Row
LastCol = DSheet.Cells(1, Dsheet.Columns.Count).End(xlToLeft).Column
'Don't include column A in your data range
Set PRange = DSheet.Cells(1, "B").Resize(LastRow, LastCol - 1)
'Define Pivot Cache (not pivot table)
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange)
'Set PCache = ActiveWorkbook.PivotCaches.Create _
'(SourceType:=xlDatabase, SourceData:=PRange). _
'CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
'TableName:="MilestonePivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="MilestonePivotTable")
'Use PSheet instead of ActiveSheet in all the following statements
'In fact, because the PTable object exists, we can just use it
'Insert Row Fields
'With AciveSheet.PivotTables("MilestonePivotTable").PivotFields("Resource Name")
'With PSheet.PivotTables("MilestonePivotTable").PivotFields("Resource Name")
With PTable.PivotFields("Resource Name")
.Orientation = xlRowField
.Position = 1
End With
With PTable.PivotFields("Deliverable")
.Orientation = xlRowField
.Position = 2
End With
'Insert Column Fields
With PTable.PivotFields("Milestone Date")
.Orientation = xlColumnField
.Position = 1
End With
I recorded a macro in which I want to create a pivot table into a new worksheet. I am using 2010 version.
I have the "Run time error 5" Invalid procedure call or argument" error when I want to run a macro. Please see the code. It creates the new sheet so is it not fine?
Range("A1").Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R17445C24", Version:=xlPivotTableVersion12).CreatePivotTable _
TableDestination:="Sheet4!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion12
Sheets("Sheet4").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Bnlunit")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Period")
.Orientation = xlColumnField
.Position = 1
End With
ActiveWindow.SmallScroll Down:=12
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Amount"), "Sum of Amount", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Hdaccount_agr_3(T)")
.Orientation = xlRowField
.Position = 1
End With
ActiveWindow.SmallScroll Down:=-33
End Sub
The problem is because of sheet name and not deleting those sheets. I think the below code could be of your help
Sub Macro1()
'
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
'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Raw Data")
'Define Data Range
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)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PRIMEPivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable_(TableDestination:=PSheet.Cells(1, 1), TableName:="PRIMEPivotTable")
'Insert Column Fields
'With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("ColumnName")
'.Orientation = xlColumnField
'.Position = 1
'End With
'Insert Row Fields
With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("RowName")
.Orientation = xlRowField
.Position = 1
End With
'Insert Data Field
With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("Field 1")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.Name = "Name of your choice"
End With
End Sub
Try the code below, explanations inside the code's comments:
Option Explicit
Sub VBAPivot()
Dim Sht1 As Worksheet
Dim NewSht As Worksheet
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim PvtRange As Range
Dim LastRow As Long
Set NewSht = ThisWorkbook.Sheets.Add ' add new sheet
Set Sht1 = ThisWorkbook.Worksheets("Sheet1")
With Sht1
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' set the PivotCach DataSource Range
Set PvtRange = .Range("A1:X" & LastRow)
End With
' Set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PvtRange.Address(False, False, xlA1, xlExternal))
' create a new Pivot Table in the new added sheet, in "A3"
Set PvtTbl = NewSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=NewSht.Range("A3"), TableName:="PivotTable1")
With PvtTbl ' modify Pivot-Table properties
With .PivotFields("Bnlunit")
.Orientation = xlPageField
.Position = 1
End With
With .PivotFields("Period")
.Orientation = xlColumnField
.Position = 1
End With
' add Field as Sum of
.AddDataField .PivotFields("Amount"), "Sum of Amount", xlSum
With .PivotFields("Hdaccount_agr_3(T)")
.Orientation = xlRowField
.Position = 1
End With
End With
End Sub
I have written below code to generate a pivot from sheet named Data it works if data is till column Z if the data goes beyond col Z. it does not work.
Need Someone to check the code & help me figure out what could be the possible error here.
Sub pivot()
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
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Data")
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(2, 2), _
TableName:="Status")
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="Status")
With ActiveSheet.PivotTables("Status").PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Status").PivotFields("Final Owner")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("Status").PivotFields("Incident ID")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "#,##0"
.Name = "Count"
End With
End Sub
Try modifying your PivotCache line to:
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange.Address(False, False, xlA1, xlExternal)). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), TableName:="Status")
Requesting help I am currently working on a macro based pivot table where we have 5 columns in Report filter.
What I am looking for is vba code for these five filer, it should show the value if the filter contains a single value else should remain as (All).
Currently I am using the following code for pivot filer:
Sub InsertPivotTable()
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Pivot").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Pivot"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Pivot")
Set DSheet = Worksheets("Report")
'Define Data Range
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)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), _
TableName:="ADT_PivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="ADT_PivotTable")
'Insert Reportfilter Fields
With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("Resp Bus Partn ID")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("ADT-File ID")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("UWY")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("SCoB - Acc")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("Curr")
.Orientation = xlPageField
.Position = 1
End With
End Sub
The answer and code are a little long, but I've added a few "Bonuses" for you, so you'll find it very useful :)
First, there is no need to delete "Pivot" sheet and re-create it just to update the PivotTable named "ADT_PivotTable", you can just update the PivotCache with the updated SourceData, and afterwards refresh the PivotTable with the updated PivotCache.
Second, I’ve added a second Sub, that check for every PivotField passed to it how many PivotItems it has, if there’s only one PivotItem then display it in the Filter, Otherwise show "All".
Sub InsertPivotTable Code
Option Explicit
Sub InsertPivotTable()
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Set PSheet = Worksheets("Pivot")
On Error GoTo 0
If PSheet Is Nothing Then ' if "Pivot" sheet doesn't exist
Set PSheet = Sheets.Add(Before:=ActiveSheet)
PSheet.Name = "Pivot"
End If
Application.DisplayAlerts = True
Set DSheet = Worksheets("Report")
'Define Data Range
With DSheet
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set PRange = .Range("A1").Resize(LastRow, LastCol) ' set data range for Pivot Table
End With
' Set the Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
On Error Resume Next
Set PTable = PSheet.PivotTables("ADT_PivotTable") ' Set the Pivot Table if already exists from previous code runs
On Error GoTo 0
If PTable Is Nothing Then ' <-- Pivot Table still doesn't exist >> create it for the first time
' create a new Pivot Table in "Pivot" sheet
Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Range("A1"), TableName:="ADT_PivotTable")
With PTable
'Insert Reportfilter Fields
With .PivotFields("Resp Bus Partn ID")
.Orientation = xlPageField
.Position = 1
End With
With .PivotFields("ADT-File ID")
.Orientation = xlPageField
.Position = 1
End With
With .PivotFields("UWY")
.Orientation = xlPageField
.Position = 1
End With
With .PivotFields("SCoB - Acc")
.Orientation = xlPageField
.Position = 1
End With
With .PivotFields("Curr")
.Orientation = xlPageField
.Position = 1
End With
End With
Else
' just refresh the Pivot cache with the updated Range
PTable.ChangePivotCache PCache
PTable.RefreshTable
End If
' modify the Filter default view for each of the Pivot Fields below
With PTable
SelectFilterSingleValue .PivotFields("Resp Bus Partn ID")
SelectFilterSingleValue .PivotFields("ADT-File ID")
SelectFilterSingleValue .PivotFields("UWY")
SelectFilterSingleValue .PivotFields("SCoB - Acc")
SelectFilterSingleValue .PivotFields("Curr")
End With
End Sub
Sub SelectFilterSingleValue Code
Sub SelectFilterSingleValue(ptFld As PivotField)
Dim PTItm As PivotItem
Dim Count As Long
With ptFld
.EnableMultiplePageItems = True
For Each PTItm In .PivotItems
If PTItm.Name <> "(blank)" Then
PTItm.Visible = True
Count = Count + 1
Else
PTItm.Visible = False
End If
Next PTItm
If Count > 1 Then
.ClearAllFilters
End If
End With
End Sub