I am trying to write some VBA that will build a pivot table in a new tab. When I run the code I am getting the Type Mismatch error when creating the PivotTable Cache.
The code is below, any help would be appreciated...hopefully a fresh look at it can spot what I am missing
Sub makeAPivotTable()
Dim sSheet, sSheet2 As Worksheet 'sSheet is where the data is, sSheet2 is where the pivot will be built
Dim cCache As PivotCache
Dim ptTable As PivotTable
Dim rRange As Range
Dim rLastRow, cLastColumn As Long
' Insert the new sheet for the pivot table to reside
Application.DisplayAlerts = False
Sheets.Add Before:=ActiveSheet
ActiveSheet.name = "PivotTable"
Application.DisplayAlerts = True
Set sSheet2 = Worksheets("PivotTable")
Set sSheet = Worksheets("Interactions db")
' define the range (the data that you want to put into the pivot table
rLastRow = sSheet.Cells(Rows.Count, 1).End(xlUp).Row
cLastColumn = sSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set rRange = sSheet.Cells(1, 1).Resize(rLastRow, cLastColumn)
' create the cache for the pivot table
Set cCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=rRange). _
CreatePivotTable(TableDestination:=sSheet2.Cells(2, 2), _
TableName:="SalesPivotTable")
' insert the blank table
Set ptTable = cCache.CreatePivotTable _
(TableDestination:=sSheet2.Cells(1, 1), TableName:="SalesPivotTable")
'Insert Row Fields
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("customer")
.Orientation = xlRowField
.Position = 1
End With
'Insert Column Fields
'With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Interaction Type")
'.Orientation = xlColumnField
'.Position = 1
'End With
'Insert Data Field
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("interactionType")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##0"
.name = "Person "
End With
' do some formatting
End Sub
Try the code below (explanations inside the code as comments)
Option Explicit
Sub makeAPivotTable()
Dim sSheet As Worksheet, sSheet2 As Worksheet ' sSheet is where the data is, sSheet2 is where the pivot will be built
Dim cCache As PivotCache
Dim ptTable As PivotTable
Dim rRange As Range
Dim rLastRow As Long, cLastColumn As Long ' need to define each one as Long, otherwise the first one is Variant
' Insert the new sheet for the pivot table to reside
Application.DisplayAlerts = False
' 2 lines below are shorter version to create a new sheet,
' assign it to sSheet2 , and name it "PivotTable"
On Error Resume Next
Set sSheet2 = Sheets("PivotTable") '<-- try to set the Sheet (already created in past code runs)
On Error GoTo 0
If sSheet2 Is Nothing Then '<-- sheet does not exist yet >> Add it
Set sSheet2 = Sheets.Add(Before:=ActiveSheet)
sSheet2.Name = "PivotTable"
End If
Application.DisplayAlerts = True
Set sSheet = Worksheets("Interactions db")
' define the range (the data that you want to put into the pivot table
With sSheet
rLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
cLastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set rRange = .Cells(1, 1).Resize(rLastRow, cLastColumn)
End With
' create the cache for the pivot table ***** THIS is the CORRECT Syntax
Set cCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rRange)
' CREATE a NEW Pivot Table in sSheet2 sheet
Set ptTable = sSheet2.PivotTables.Add(PivotCache:=cCache, TableDestination:=sSheet2.Range("A1"), TableName:="SalesPivotTable")
With ptTable
'Insert Row Fields
With .PivotFields("customer")
.Orientation = xlRowField
.Position = 1
End With
'Insert Column Fields
'With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Interaction Type")
'.Orientation = xlColumnField
'.Position = 1
'End With
'Insert Data Field
With .PivotFields("interactionType")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##0"
.Name = "Person "
End With
' do some formatting
End With
End Sub
Related
I have a use case where I filter the column values in a pivot and then change the value field settings of the pivot table. I am creating the pivot table and the sheet every time while deleting the previous one. My problem is that I am unable to get one column to reflect in the pivot but the values are correct in the grand total. My code is below:
Sub createPivotandFilter()
'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
Dim pf As PivotField
Dim PItems As PivotItem
'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("Data_TB Detail")
'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(3, 1), _
TableName:="VariancePivot")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="VariancePivot")
With ActiveSheet.PivotTables("VariancePivot")
.InGridDropZones = True
.RowAxisLayout xlTabularRow
End With
'Insert Column Fields
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Period")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("VariancePivot").PivotFields("LE")
.Orientation = xlColumnField
.Position = 2
End With
'Insert Row Fields
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Mapped up 1st level")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Account")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("VariancePivot").PivotFields("Description")
.Orientation = xlRowField
.Position = 3
End With
'Insert Data Field
With ActiveSheet.PivotTables("VariancePivot").PivotFields("USD")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##0"
.Name = "Sum of USD"
.Calculation = xlDifferenceFrom
.BaseField = "Period"
.BaseItem = "Jun 30,2018"
End With
'adding the filter
Set PTable = ActiveSheet.PivotTables("VariancePivot")
Set pf = PTable.PivotFields("Period")
PTable.RefreshTable
temp = pf.PivotItems.Count
For i = 1 To temp
If pf.PivotItems(i).Value = "Jun 30,2018" Or pf.PivotItems(i).Value = "Sep 30,2018" Then
pf.PivotItems(i).Visible = True
Else
pf.PivotItems(i).Visible = False
End If
Next
End Sub
A screenshot of the result:
Any help is much appreciated.
I have a pivot table macro that two row fields and one value column. I am trying to figure out how I could right an If Statement that would detect if there is no number in the "Adjustment Amount" the detail will be closed in the column called "ledger". Below is the code I have:
Sub MakeAPivotTable()
Dim pt As pivotTable 'Creates pivot table
Dim pc As PivotCache 'Pivot Cache
Dim pf As PivotField 'Pivot Field
Dim pi As PivotItem
Dim PRange As Range 'Source data range
Dim lastRow As Long 'Last Row of Report even if it changes
Dim lastCol As Long 'Last Column of Report even if it changes
Dim DSheet As Worksheet 'Claiming "Report" sheet as data sheet
Dim PSheet As Worksheet 'Claiming what is pivot sheet for this macro
Dim ptType As String
Dim ADJ As Range
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Metrics").Delete
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Metrics"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Metrics")
Set DSheet = Worksheets("Report")
With ActiveWorkbook.Sheets("Metrics").Tab
.Color = 4555
.TintAndShade = 0
End With
'Defining Data Range. Taking the first cell of the data table and select uptp the last row and then up to the last column
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)
'Create pivot cache. Defines Pivot Cache by using Data source and defines the cell address in the new worksheet to insert pivot table
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), TableName:="Accrual")
'Insert Pivot Table
Set pt = pc.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="Accrual")
'Putting Row Fields in
With ActiveSheet.PivotTables("Accrual").PivotFields("Ledger Name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Accrual").PivotFields("CC")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("Accrual").CompactLayoutRowHeader = "Ledger"
'Putting Values Field in
ActiveSheet.PivotTables("Accrual").AddDataField ActiveSheet.PivotTables( _
"Accrual").PivotFields("Adjustment Amt"), "Sum of Adjustment Amt", _
xlSum
ActiveSheet.PivotTables("Accrual").DataPivotField.PivotItems( _
"Sum of Adjustment Amt").Caption = "Adjustment Amount"
With ActiveSheet.PivotTables("Accrual").PivotFields("Adjustment Amount")
.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(#_)"
End With
And this is what I thought would work:
For Each ADJ In Worksheets("Metrics").Range("C3:C100")
If ADJ = "" Then
ActiveSheet.PivotTables("Accrual").PivotFields("Ledger Name").Selection.ShowDetail = False
End If
Next
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
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
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