Error while creating PivotTable - vba

I am writing a code to create an Pivot table. I recorded the macros, and then simplified it to easy understanding.
While executing the code, I get error
subscript out of range.
I checked with the worksheet name, it is the same name I have defined.
I'm clueless, why it is not working. Below, is the code I tried.
Sub table()
Dim pvtcache As PivotCache
Dim pvttbl As pivottable
Dim pvtsht As Worksheet
Set pvtcache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Preparation Sheet!R1C1:R1048576C9")
Set pvtsht = Worksheets("LP")
On Error Resume Next
Set pvttbl = pvtsht.PivotTables("PivotTable3")
On Error GoTo 0
If pvttbl Is Nothing Then
Set pvttbl = pvtsht.PivotTables.Add(PivotCache:=pvtcache, TableDestination:=pvtsht.Range("A3"), TableName:="PivotTable3")
With pvttbl
With .PivotFields("DL")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
End With
Else
' just refresh the Pivot cache with the updated Range
pvttbl.ChangePivotCache pvtcache
End If
End Sub
below is the code, from macros
Sub Macro8()
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Preparation Sheet!R1C1:R1048576C9", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet4!R3C1", TableName:="PivotTable2" _
, DefaultVersion:=xlPivotTableVersion15
Sheets("Sheet4").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable2").PivotFields("DL")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable2").AddDataField ActiveSheet.PivotTables( _
"PivotTable2").PivotFields("Colour"), "Count of Colour", xlCount
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
End Sub

If your worksheet names contain spaces "Preparation Sheet!R1C1:R1048576C9" you need to enclose the worksheet name in ''
"'Preparation Sheet'!R1C1:R1048576C9"
or avoid spaces in it.
Edit
Add this function to your module
Public Function PivotTableExistsInWorksheet(pvWorksheet As Worksheet, pvTableName As String) As Boolean
Dim pvTable As PivotTable
PivotTableExistsInWorksheet = False 'Default
For Each pvTable In pvWorksheet.PivotTables
If pvTable.Name = pvTableName Then
PivotTableExistsInWorksheet = True
Exit Function
End If
Next pvTable
End Function
and use
If PivotTableExistsInWorksheet(pvtsht, "PivotTable3") Then
Set pvttbl = pvtsht.PivotTables("PivotTable3")
End If
instead of the On Error Resume Next … Goto 0 block to see if this works.

Related

Unable to create pivot ina new worksheet in VBA

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

Excel VBA: Creating Pivot Table in Specific Destination without Error?

I've been extensively looking into creating a pivot table through vba, and am facing some complications I can't find a solution to. I am trying to create a pivot table in column 4 of the sheet "Pivot". When I try to run my code I get:
"Run time Error 1004: PivotTableWizard method of Worksheet class failed."
Can anyone help? I am still very new to vba.
Here is my code, I keep getting error on the second line:
Sub PivotTable()
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=Sheets("Information").UsedRange).CreatePivotTable TableDestination:="Pivot!R1C4", TableName:="PivotTable", DefaultVersion:=xlPivotTableVersion10
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(1, 1)
With ActiveSheet.PivotTables("PivotTable").PivotFields("PN")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Commit")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable").AddDataField ActiveSheet.PivotTables("PivotTable").PivotFields("Qty"), "Sum", xlSum
End Sub
You are looking for something like the code below (explanation inside the code comments) :
Option Explicit
Sub AutoPivotTable()
Dim Sht As Worksheet
Dim PvtSht As Worksheet
Dim SrcData As Range
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
'-- Determine the data range you want to pivot --
' Set the Worksheet object
Set Sht = ThisWorkbook.Worksheets("Information")
Set SrcData = Sht.UsedRange '1:Z10000").Address(False, False, xlR1C1, xlExternal)
' Set the Pivot Cache from Source Data
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData.Address(False, False, xlA1, xlExternal))
' Set the Worksheet object where the Pivot Table will be loated
Set PvtSht = ThisWorkbook.Worksheets("Pivot")
On Error Resume Next
'Set the pivot table object
Set PvtTbl = PvtSht.PivotTables("PivotTable") ' check if "PivotTable" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then '<-- Pivot Table not created >> create it
' create a new Pivot Table in "Pivot" sheet
Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("D1"), TableName:="PivotTable")
With PvtTbl
With .PivotFields("PN")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Commit")
.Orientation = xlColumnField
.Position = 1
End With
.AddDataField .PivotFields("Qty"), "Sum of Qty", xlSum
End With
Else ' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

vba to create a pivot table excel 2015

I wanted to create a Pivot table in Excel 2015.
I recorded the macros to create my own vba code. But I couldn't make it. Also, I referred the links available here, but I couldn't make it out from them because they followed other way, which was hard for me.
Could anyone help me to frame the VBA code for the below recorded macros and explain in the comment the steps? This would be really helpful for me as I am generating the Pivot table in vba for first time.
Sub Macro4()
'
' Macro4 Macro
'
'
Cells.Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Preparation sheet!R1C1:R1048576C8", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet21!R3C1", TableName:="PivotTable7" _
, DefaultVersion:=xlPivotTableVersion15
Sheets("Sheet21").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Category")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Category")
.PivotItems("DG-035583").Visible = False
.PivotItems("DG-048917").Visible = False
.PivotItems("DG-Series").Visible = False
.PivotItems("gn").Visible = False
.PivotItems("yl").Visible = False
.PivotItems("(blank)").Visible = False
End With
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Colour")
.PivotItems("(blank)").Visible = False
End With
End Sub
Try the code below to create/update a PivotTable, explanations inside the code as comments:
Option Explicit
Sub AutoPivot()
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim PvtSht As Worksheet
' set Pivot Cache for Pivot Table
' Your range is static, there are ways to refer to a dynamic range
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Preparation sheet!R1C1:R1048576C8")
' set the Pivot table's sheet
Set PvtSht = Worksheets("Sheet21")
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = PvtSht.PivotTables("PivotTable7") ' check if "PivotTable7" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' Pivot table object is nothing >> create it
' create a new Pivot Table in "PivotTable4" sheet
Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("A3"), TableName:="PivotTable7")
With PvtTbl
With .PivotFields("Category")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Colour")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Category")
.PivotItems("DG-035583").Visible = False
.PivotItems("DG-048917").Visible = False
.PivotItems("DG-Series").Visible = False
.PivotItems("gn").Visible = False
.PivotItems("yl").Visible = False
.PivotItems("(blank)").Visible = False
End With
With .PivotFields("Colour")
.PivotItems("(blank)").Visible = False
End With
End With
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

Run-time error '13': Type mismatch in Macro

I have recorded a macro to create a Pivot Chart. The Data Source is defined as a variable because the data keeps on changing. The macro ran well for a fewer number of rows (up till 20 no.). But as the data increases beyond the 20 no. of rows, the macro shows a
Run-time error 13: Type mismatch.
The code is as below. The highlighted part shows error
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "COMPARISON" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "COMPARISON"
Sheets("FRONT PAGE").Select
Nobid = Cells(11, 4)
Sheets("ARRANGED BIDS").Select
Finalrow = Cells(Rows.Count, 1).End(xlUp).Row
**ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("ARRANGED BIDS").Range(Cells(2, 1), Cells(Finalrow, (7 + 2 * Nobid))), Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="COMPARISON!R1C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion15**
Sheets("COMPARISON").Select
Cells(1, 1).Select
ActiveWorkbook.ShowPivotTableFieldList = True
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("COMPARISON!$A$1:$C$18")
ActiveSheet.Shapes("Chart 1").IncrementLeft 192
ActiveSheet.Shapes("Chart 1").IncrementTop 15
With ActiveChart.PivotLayout.PivotTable.PivotFields("Item No.")
.Orientation = xlRowField
.Position = 1
End With
With ActiveChart.PivotLayout.PivotTable.PivotFields("Item Description")
.Orientation = xlRowField
.Position = 2
End With
With ActiveChart.PivotLayout.PivotTable.PivotFields("Quantity")
.Orientation = xlRowField
.Position = 3
End With
ActiveWindow.SmallScroll Down:=-6
With ActiveChart.PivotLayout.PivotTable.PivotFields("Item No.")
.Orientation = xlRowField
.Position = 3
End With
With ActiveChart.PivotLayout.PivotTable.PivotFields("Quantity")
.Orientation = xlRowField
.Position = 1
End With
Please, someone, help me resolve the error.
Thanks
Try the code below, it should take of you error, and all the PivotTable setting. Explanation are inside the code comments.
Note: I’ve removed all of the unqualified Range and Cells, and also the un-necessary Select, which slows the code down.
Code
Option Explicit
Sub copy_to_report()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim PvtRng As Range
Dim ws As Worksheet
'Dim t As String
Dim i As Long
Dim FinalRow As Long
Dim Nobid As Long
Application.DisplayAlerts = False
' loop through all sheets, if one of them is name "COMPARISON" delete it
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "COMPARISON" Then ws.Delete
Next ws
Application.DisplayAlerts = True
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = "COMPARISON"
' ***** THIS is the only variable I'm not sure what it's used for *****
Nobid = Sheets("FRONT PAGE").Cells(11, 4)
With Sheets("ARRANGED BIDS")
' find last row in column "A" in "ARRANGED BIDS" sheet
FinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
' set the Range for the Pivot Cache
Set PvtRng = .Range(.Cells(2, 1), .Cells(Finalrow, (7 + 2 * Nobid)))
End With
' Option 1: Set Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PvtRng)
' Option 2: Set Pivot Cache
'Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PvtRng.Address(True, True, xlA1, True))
' create a new Pivot Table in "COMPARISON" sheet
Set PvtTbl = ws.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=ws.Range("A1"), TableName:="PivotTable1")
End Sub
Either you try this...
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("ARRANGED BIDS").Range(Cells(2, 1), Cells(Finalrow, (7 + 2 * Nobid))), Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="COMPARISON!A1", TableName:="PivotTable1"
Or try it like this...
Dim pc As PivotCache
Dim pt As PivotTable
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("ARRANGED BIDS").Range(Cells(2, 1), Cells(Finalrow, (7 + 2 * Nobid))), Version:=xlPivotTableVersion15)
Set pt = pc.CreatePivotTable(TableDestination:="COMPARISON!A1", TableName:="PivotTable1")
if you want to create a pivot, here is what i use. Remove all the "xl." from code, i was creating them on new excel and saved them.
Dim wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set wb = xl.ActiveWorkbook
Set ws = wb.Sheets("Data")
Set rng1 = ws.Cells.Find("*", ws.[a1], xlFormulas, , , xlPrevious)
xl.Worksheets.Add
xl.ActiveSheet.Name = "Pivot"
xl.Worksheets("Pivot").Activate
xl.ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Data!R1C1:R" & CStr(rng1.Row) & "C" & CStr(rng1.Column), Version:=xlPivotTableVersion15).CreatePivotTable _
TableDestination:="Pivot!R3C1", TableName:="PivotTable3", DefaultVersion _
:=xlPivotTableVersion15
xl.Sheets("Pivot").Select
xl.ActiveWorkbook.ShowPivotTableFieldList = True
With xl.ActiveSheet.PivotTables("PivotTable3").PivotFields("IC Status")
.Orientation = xlRowField
.Position = 1
End With
With xl.ActiveSheet.PivotTables("PivotTable3").PivotFields("CompCode")
.Orientation = xlRowField
.Position = 2
End With
With xl.ActiveSheet.PivotTables("PivotTable3").PivotFields("Aging from last action in PD")
.Orientation = xlColumnField
.Position = 1
End With
With xl.ActiveSheet.PivotTables("PivotTable3").PivotFields("PD#")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "0"
.Name = "Count of PD#"
End With
xl.ActiveSheet.PivotTables("PivotTable3").HasAutoFormat = False
Dim j As Variant
xl.ActiveSheet.PivotTables("PivotTable3").PivotFields("IC Status"). _
EnableMultiplePageItems = True
With xl.ActiveSheet.PivotTables("PivotTable3").PivotFields("IC Status")
For j = 1 To .PivotItems.Count
DoEvents
.PivotItems(.PivotItems(j).Name).Visible = False
With xl.ActiveSheet.PivotTables("PivotTable3").PivotFields("IC Status")
On Error Resume Next
.PivotItems("In progress AP Timisoara").Visible = True
End With
Next j
End With

Pivot Table VBA Error from Recorded Macro

Below is my update to the code. TableX is the referenced table that my pivot tables will use. After declaring the 'shtReport' variable as a Worksheet and further naming the variable, the error 'Object variable or With block variable not set' occurs.
Option Explicit
Sub SutoPivot()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim shtReport As Worksheet
' set the Pivot Cache (NOT SURE what is "TableX" ?)
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="TableX", Version:=xlPivotTableVersion14)
Set shtReport = Worksheets("Invoice Data")
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = Worksheets("Invoice Data").PivotTables("PivotTable1a")
On Error GoTo 0
If PvtTbl Is Nothing Then
' create a new Pivot Table in "Invoice Data" sheet, start from Cell Y1
Set PvtTbl = shtReport.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=Worksheets("Invoice Data").Range("Y1"), _ TableName:="PivotTable1a")
With PvtTbl.PivotFields("Sales Director")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Manager")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Owner")
.Orientation = xlRowField
.Position = 3
End With
With PvtTbl.PivotFields("Account Name")
.Orientation = xlRowField
.Position = 4
End With
With PvtTbl.PivotFields("Business Name")
.Orientation = xlRowField
.Position = 5
End With
With PvtTbl.PivotFields("Annual Aggregate Volume")
.Orientation = xlValuesField
.Position = 1
End With
PvtTbl.AddDataField PvtTbl.PivotFields("Annual Aggregate Volume"),
"Sum of Annual Aggregate Volume", xlSum
With PvtTbl.PivotFields("Sum of Annual Aggregate Volume")
.NumberFormat = "#,##0"
End With
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub
The code below will get you started on automating the creation and updating of PivotTables in VBA:
Option Explicit
Sub SutoPivot()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
' set the Pivot Cache (NOT SURE what is "TableX" ?)
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="TableX", Version:=xlPivotTableVersion14)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = Worksheets("Invoice Data").PivotTables("PivotTable1a")
On Error GoTo 0
If PvtTbl Is Nothing Then
' create a new Pivot Table in "Invoice Data" sheet, start from Cell Y1
Set PvtTbl = shtReport.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=Worksheets("Invoice Data").Range("Y1"), TableName:="PivotTable1a")
With PvtTbl.PivotFields("Director")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Manager")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Owner")
.Orientation = xlRowField
.Position = 3
End With
With PvtTbl.PivotFields("Account Name")
.Orientation = xlRowField
.Position = 4
End With
With PvtTbl.PivotFields("Business Name")
.Orientation = xlRowField
.Position = 5
End With
PvtTbl.AddDataField PvtTbl.PivotFields("Annual Aggregate Volume"), _
"Sum of Annual Aggregate Volume", xlSum
With PvtTbl.PivotFields("Sum of Annual Aggregate Volume")
.NumberFormat = "#,##0"
End With
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub