I am creating a macro to generate some clustered column pivot charts. I have used examples from the internet/stack overflow to generate the pivot table, generate the pivot chart and display the columns in decreasing order.
I have consulted the Microsoft Documentation and tried fiddling with the syntax of PivotField.Autosort.
Here is a generalised version of my code with comments. The Autosort command to display the columns in descending order is the last two lines:
'Declare Variables
Dim PSheet As Worksheet 'To create a sheet for a new pivot table.
Dim DSheet As Worksheet 'To use as a data sheet.
Dim PCache As PivotCache 'To use as a name for pivot table cache.
Dim PTable As PivotTable 'To use as a name for our pivot table.
Dim PRange As Range 'to define source data range.
Dim LastRow As Long 'To get the last row and column of our data range.
Dim LastCol As Long '
Dim chtObj As ChartObject
Dim PvtSht As Worksheet
Dim PvtTbl As PivotTable
'After inserting a new worksheet, this code will set the value of FSheet
'variable to pivot table worksheet and DSheet to source data worksheet.
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("MaintActivType").Delete
Worksheets("Sheet1").Select
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "MaintActivType"
Application.DisplayAlerts = True
Set PSheet = Worksheets("MaintActivType")
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.Cells(1, 1).Resize(LastRow, LastCol)
'Define Pivot Cache
'In Excel 2000 and above, before creating a pivot
'table you need to create a pivot cache to define the data source.
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="MaintenanceData")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="MaintenanceData")
'Insert Row Fields
With ActiveSheet.PivotTables("MaintenanceData").PivotFields("MaintActivType")
.Orientation = xlRowField
.Position = 1 'this field allows for sub-categories of data to be displayed
End With
'Insert Column Fields
With ActiveSheet.PivotTables("MaintenanceData").PivotFields("MaintActivType")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.Name = "Count of MaintActivType"
End With
' set the Pivot sheet
Set PvtSht = Sheets("MaintActivType")
' set the Pivot Table object
Set PvtTbl = PvtSht.PivotTables("MaintenanceData")
' set the Chart Object
Set chtObj = PvtSht.ChartObjects.Add(300, 200, 550, 200)
' modify ChartObject properties
With chtObj
.Chart.SetSourceData PvtTbl.TableRange2 ' set the chart's data range to the Pivot-Table's TableRange2
.Chart.ChartType = xlColumnClustered
.Name = "Maintenance Activity Type"
.Chart.HasTitle = True
.Chart.ChartTitle.Text = "Maintenance Activity Type"
.Chart.HasLegend = False
End With
ActiveSheet.PivotTables("MaintenanceData").PivotField("MaintActivType") _
.AutoSort xlDescending, "Sum of MaintActivType"
'End With
I don't get any error messages associated with the Autosort command, but if I comment out the On Error Resume Next I get a Type mismatch error for the pivot cache creation ("Set Pcache ..."), which is baffling because that part works just fine with the error message suppressed.
"that part works just fine with the error message suppressed" it doesn't work fine, it just doesn't matter that it doesn't work.
Dim PCache As PivotCache
'...
'...
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="MaintenanceData")
Here you create a pivotcache, but then use it to create a pivottable, and try to assign that pivottable to your PCache variable (which can only be used for a pivotcache...) So that raises a run-time error, but by that point the pivottable is created, and you pick that up on the next line.
VBA Copy Pivot Table to New Sheet
Related
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 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 that generated a very simple pivot table. When I played the macro back I get an error in the PivotTable.
I get:
Invalid procedure call or argument
So I went back and put single quotes around the SourceData and TableDestination. Now I get a pivot table but only with the total. It should give me the count of all the occurrences of the items in Column A.
Here's the code
Sub testpivot()
'
' testpivot Macro
'
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"'GF Response Detail R'!R1C1:R65536C1", Version:= _
xlPivotTableVersion10).CreatePivotTable TableDestination:= _
"'GF Response Detail R'!R2C10", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion10
Sheets("GF Response Detail R").Select
Cells(2, 7).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Region"), "Count of Region", xlCount
ActiveWorkbook.ShowPivotTableFieldList = False
End Sub
You want to remove the Pivot Table from the worksheet. Before you run the macro.
The code below will check first if there's a "PivotTable1" in the sheet, and if it does it will delete it.
Afterwards, it will create a new PivotTable on "GF Response Detail R" sheet, with the updated data in Column "A".
Code
Option Explicit
Sub testpivot()
' testpivot Macro
Dim PivTbl As PivotTable
Dim PivCache As PivotCache
Dim DataSht As Worksheet
Dim lastRow As Long
Dim SrcRng As Range
Dim SrcData As String
' set the Pivot Data
Set DataSht = Worksheets("GF Response Detail R")
With DataSht
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row '<-- get last row in Column A
Set SrcRng = .Range("A1:A" & lastRow) '<-- set dynamic Pivot Range
SrcData = SrcRng.Address(True, True, xlA1, xlExternal) '<-- get the Range Address, including sheet's name
End With
'-- first check if there's a "PivotTable1" in sheet >> if Yes, Delete it
For Each PivTbl In DataSht.PivotTables
If PivTbl.Name = "PivotTable1" Then
DataSht.Range(PivTbl.TableRange2.Address).Delete Shift:=xlUp
Exit For
End If
Next PivTbl
' set the Pivot Cache
'Set PivCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
' Option 2: set the Pivot Cache
Set PivCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcRng)
' Option 3: set the Pivot Cache
Set PivCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData, Version:=xlPivotTableVersion15)
' create a new Pivot Table in "EXP Pivot" sheet, start from Cell A1
Set PivTbl = DataSht.PivotTables.Add(PivotCache:=PivCache, TableDestination:=DataSht.Range("J2"), TableName:="PivotTable1")
With PivTbl
With .PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
.AddDataField .PivotFields("Region"), "Count of Region", xlCount
ActiveWorkbook.ShowPivotTableFieldList = False
End With
End Sub
Here try this. It is a slight variation of what #Shai Rado was suggesting.
Sub RegionMacro()
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
'define the sheet, last row, and pivot table range
Set DSheet = Worksheets("GF Response Detail R")
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
Set PRange = DSheet.Range("A1:A" & LastRow)
'get address of range
sData = PRange.Address(False, True)
'check to see if the table already exist and delete it if it does
For Each PTable In DSheet.PivotTables
If PTable.Name = "RegionCountTable" Then
DSheet.Range(PTable.TableRange2.Address).Delete Shift:=xlUp
Exit For
End If
Next PTable
'define the pivot cache
Set PCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
'insert a blank pivot table into cell G2 and call it "RegionCountTable"
Set PTable = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(2, 7), TableName:="RegionCountTable")
'insert row fields
With PTable
With ActiveSheet.PivotTables("RegionCountTable").PivotFields("Region")
.Orientation = xlRowField
.Position = 1
End With
'create a count for the region
.AddDataField .PivotFields("Region"), "Count of Region", xlCount
ActiveWorkbook.ShowPivotTableFieldList = False
End With
End Sub
I am not able to run this, I want to count total rows in sheet and pass that to pivot chart to create.
Pivot chart create
select fileds
Double click grand total to create new spread sheet
Sub Macro2()
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ActiveSheet
NewSheet = ActiveSheet.Name
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
ws & "!R1C1:R" & lastRow & "C15",
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:=NewSheet & "!R1C1", TableName:="PivotTable1",
DefaultVersion _
:=xlPivotTableVersion14
Sheets("NewSheet").Select
Cells(1, 1).Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range("Sheet4!$A$1:$C$18")
ActiveSheet.Shapes("Chart 1").IncrementLeft 192
ActiveSheet.Shapes("Chart 1").IncrementTop 15
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Customer")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables(
_
"PivotTable1").PivotFields("Customer"), "Count of Customer", xlCount
ActiveWindow.SmallScroll Down:=12
Range("B29").Select
Selection.ShowDetail = True
End Sub'
The code below checks the data in Sheet1 (modify to your sheet name) and creates a Pivot Table and Chart in Sheet Report.
On first time it creates the Pivot Table and chart, from the second time it just refreshes the Pivot Cache with the updated rows of data (in Sheet1) and updates the Chart.
Sub Macro2()
Dim sht1 As Worksheet
Dim shtReport As Worksheet
Dim lastRow As Long
Dim PivotSrc_Range As Range
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim Chart1 As Chart
' modify to your sheet name
Set sht1 = ThisWorkbook.Sheets("Sheet1")
' modify to your desired Pivot Table location
Set shtReport = ThisWorkbook.Sheets("Report")
' create the Source Range of the Pivot Cache
lastRow = sht1.Cells(sht1.Rows.Count, "A").End(xlUp).Row
' it's looking uo tp Column "O" (15) as recorded in your MACRO
Set PivotSrc_Range = sht1.Range(sht1.Cells(1, 1), sht1.Cells(lastRow, 15))
' set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PivotSrc_Range, Version:=xlPivotTableVersion14)
On Error Resume Next
Set PvtTbl = shtReport.PivotTables("PivotTable1")
On Error GoTo 0
If PvtTbl Is Nothing Then
' create a new Pivot Table in "Report" sheet, start from Cell A2
Set PvtTbl = shtReport.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=shtReport.Range("A2"), TableName:="PivotTable1")
' modify the name in brackets according to your Pivot Fields
With PvtTbl.PivotFields("Customer")
.Orientation = xlRowField
.Position = 1
End With
PvtTbl.AddDataField PvtTbl.PivotFields("Customer"), "Count of Customer", xlCount
Else
' just refresh the Pivot cache with the updated Range (data in Sheet1)
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
' check if already has a chart in sheet (from previous Macro Runs)
If shtReport.ChartObjects.Count >= 1 Then
Set Chart1 = shtReport.ChartObjects(1).Chart
Else ' first time >> create the chart
shtReport.Shapes.AddChart.Select
Set Chart1 = ActiveChart
End If
With Chart1
.ChartType = xlColumnClustered
.SetSourceData Source:=PvtTbl.TableRange1 ' refresh the chart with the updated Pivot Table
End With
End Sub