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
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 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 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
I have recorded a macro for inserting a pivot. Since the macro is recorded it works fine with the specific excel sheet. But I want to generalize it such that it works on all sheets irrespective of the number of rows. So I want to select the 'N' column starting from 'N6' to the last filled cell. This I did using,
Range(Range("N5"), Range("N5").End(xlDown)).Select
But I want a dynamic destination for the pivot. It should be a couple of rows below the last filled rows in the sheet. How do I do that?
Sub Macro2()
Range("N6:N31").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R6C14:R31C14", Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Sheet1!R38C11", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet1").Select
Cells(38, 11).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("BREAK TYPE")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("BREAK TYPE"), "Count of BREAK TYPE", xlCount
Range("K38").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("BREAK TYPE")
.Orientation = xlRowField
.Position = 1
End With
ActiveWorkbook.ShowPivotTableFieldList = False
End Sub
The code below checks for last row with data in Column N, then it checks if there is already a Pivot Table in "Sheet1".
If there is, it just refreshes the Pivot cache, according to updated Data.
If there isn't, it creates a PivotTable (2 rows under - Not Recommended).
Option Explicit
Sub Macro2()
Dim shtPivot As Worksheet
Dim PivotSrc_Range As Range
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim lastRow As Long
' modify to your Sheet name that holds the Pivot source data
Set shtPivot = ThisWorkbook.Sheets("Sheet1")
With shtPivot
lastRow = .Cells(.Rows.Count, "N").End(xlUp).Row
' setting dynamic Range in Column N
Set PivotSrc_Range = Range("N6:N" & lastRow)
' for debug
Debug.Print PivotSrc_Range.Address
End With
' set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PivotSrc_Range, Version:=xlPivotTableVersion14)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = shtPivot.PivotTables("PivotTable1")
On Error GoTo 0
If PvtTbl Is Nothing Then
' create a new Pivot Table in "Sheet1" sheet, start 3 rows below your last line with data
Set PvtTbl = shtPivot.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=shtPivot.Range("N" & lastRow + 3), TableName:="PivotTable1")
' modify the name in brackets according to your Pivot Fields
With PvtTbl.PivotFields("BREAK TYPE")
.Orientation = xlRowField
.Position = 1
End With
PvtTbl.AddDataField PvtTbl.PivotFields("BREAK TYPE"), "Count of BREAK TYPE", xlCount
Else
' just refresh the Pivot cache with the updated Range (data in Sheet1)
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
ActiveWorkbook.ShowPivotTableFieldList = False
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