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
Related
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
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 created a Macro for making a Pivot Table in Sheet "Pivot" from Data Sheet "Sheet1".
Although I am able to run the macro in my system but in other systems, it gives a Runtime Error 5 at ActiveWorkbook.PivotCaches.Create line.
Sub Make_Pivot()
'
' Make_Pivot Macro
Sheets("Sheet1").Select
Columns("D:G").Select
Range("G1").Activate
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C4:R1048576C7", Version:=6).CreatePivotTable TableDestination:= _
"Pivot!R1C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Pivot").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("NDL")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Tracking IDs"), "Count of Tracking IDs", xlCount
Columns("A:B").Select
Range("B1").Activate
Selection.Copy
Range("G13").Select
Sheets("Count").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("F18").Select
End Sub
Try the dynamic code below (explanations inside the code as comments):
Option Explicit
Sub Make_Pivot()
' Make_Pivot Macro
Dim WB As Workbook
Dim ws As Worksheet
Dim PvtSht As Worksheet
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim SrcData As Range
Dim LastRow As Long
' set the workbook object
Set WB = ThisWorkbook
' set the worksheet object where the Pivot-Table will be
Set PvtSht = ThisWorkbook.Worksheets("Pivot")
' set the worksheet object where the Data lies
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
LastRow = .Cells(.Rows.Count, "G").End(xlUp).Row ' <-- last row in column "G"
' set the Pivot-Cache SourceData object
Set SrcData = .Range("D1:G" & LastRow)
End With
' Create the Pivot Cache
Set PvtCache = WB.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=SrcData.Address(False, False, xlA1, xlExternal))
' === FOR DEBUG ONLY ===
MsgBox PvtCache.SourceData
' Set the Pivot Table Object (already created in previous macro run)
On Error Resume Next
Set PvtTbl = PvtSht.PivotTables("PivotTable1")
On Error GoTo 0
If PvtTbl Is Nothing Then ' <-- pivot table still doesn't exist >> need to create it
' create a new Pivot Table in "Pivot" sheet, start from Cell A1
Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("A1"), TableName:="PivotTable1")
With PvtTbl
With .PivotFields("NDL")
.Orientation = xlRowField
.Position = 1
End With
.AddDataField .PivotFields("Tracking IDs"), "Count of Tracking IDs", xlCount
End With
Else
' just refresh the Pivot table, with updated Pivot Cache
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
' rest of your code goes here ...
End Sub
Note: There's no need to use so many Select and Selection, instead use fully qualifed Range, Worksheet and Objects.
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 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