Create Calculated field in Pivot Table using VBA - excel

I need the expert help. I want to implement one formula for particular column on Pivot Table created by VB code.
I have written the code that will create the Pivot table with Count the Repeat Data and would like to next column will populate with predefined formula while generating the pivot table by button click event.
Formula will be implemented on column ā€œCā€ as below by using PIVOT Table generation code using VBA module
=IF(AND(B2>=0,B2<=2),1,IF(AND(B2>=3,B2<=5),2,IF(AND(B2>=6,B2<=10),3,IF(AND(B2>=11,B2<=15),4,IF(B2>=16,5)))))
Source worksheet (Rawdata):
Current code and Pivot table :
My current VBA source code for generation of Pivot Table:
Sub PivotTableModule()
'Insert Pivot Table
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Pivot").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Pivot"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Pivot")
Set DSheet = Worksheets("Rawdata")
DSheet.AutoFilterMode = False
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange)
'CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), _
TableName:="SalesPivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="PivotTable")
'Insert Row Fields
With PTable.PivotFields("FailureMode")
.Orientation = xlRowField
.Position = 1
End With
'Insert Data Field
With PTable.PivotFields("FailureMode")
.Orientation = xlDataField
.Position = 1
.Description = "Sum of FailureMode"
.Function = xlCount ' xlSum
.NumberFormat = "#,##0"
.Name = "RepeatCount"
End With
End Sub
Current Output (Pivot Generated by Code)
My Expected Pivot Table would be as below :
Formula on Column 'C' while creating the Pivot table
=IF(AND(B2>=0,B2<=2),1,IF(AND(B2>=3,B2<=5),2,IF(AND(B2>=6,B2<=10),3,IF(AND(B2>=11,B2<=15),4,IF(B2>=16,5)))))
HI, I have tried with the Pivot Table Calculated Fields but I am getting the error. I don't know the code is correct or not.
Sub PivotCalculatedFormula()
Dim PvtTbl As PivotTable
Set PvtTbl = Worksheets("Pivot").PivotTables("PivotTable")
'for empty cells in the data area of a PivotTable report, show a specified value, using the PivotTable.NullString Property:
PvtTbl.NullString = "0"
PvtTbl.DisplayNullString = True
PvtTbl.CalculatedFields.Add Name:="RPN", Formula:="=IF(AND(RepeatCount>=0,RepeatCount<=2),1,IF(AND(RepeatCount>=3,RepeatCount<=5),2,IF(AND(RepeatCount>=6,RepeatCount<=10),3,IF(AND(RepeatCount>=11,RepeatCount<=15),4,IF(RepeatCount>=16,5)))))"
With PvtTbl.PivotFields("RPN")
.Orientation = xlDataField
.Function = xlSum
.Position = 3
.NumberFormat = "0.00%"
.Caption = "RPN-%"
End With
End Sub

Related

Currently writing code to create a pivot table that will show the count of IDS that are within a city under a county. My macro only creates a sheet

I got the code from elsewhere and tried to adapt it to my worksheet but it only creates a blank sheet and not the table. I am thinking that there is some error when it tries to get grab the data from the source sheet.
Is there a different way to to fix it or maybe create this table if we can't fix it? Like for example the data is dynamic meaning that each report has a different amount of rows and perhaps later on columns.
for ex:
ID
Name
city
County
23423
Jdoe
d city
d County
That said there are about 30 other columns that are in the report and in the future there may or may not be more columns. The amount of rows number in the 10s of thousands and can be different week to week. I am trying to create a pivot table put an ID to the city they are in and the county it is listed under. I have already created or adapted a different macro to format the document in how we can use it but the pivot table is the last step. Please help!!!
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
' Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
'define worksheet
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("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:="CountyTable")
' Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="CountyTable")
'Insert Row "County" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields("PATIENT_COUNTY")
.Orientation = xlRowField
.Position = 1
End With
'Insert Row "City" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields("PATIENT_CITY")
.Orientation = xlRowField
.Position = 2
End With
'Insert Values "Count of PID" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields( _
"Sum of PATIENT_LOCAL_ID")
.Caption = "Count of PATIENT_LOCAL_ID"
.Function = xlCount
End With
'Format Pivot Table
ActiveSheet.PivotTables("CountyTable").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("CountyTable").TableStyle2 = "PivotStyleMedium9"
End Sub

VBA Find Amount Differences Between Books and Sub-Books

I have two large data sets of 70,000+ records which may be more or less depending on the day. Sheet 1 has the information pulled from today and Sheet 2 has the information from yesterday. These are accounting series.
Column E has the region. Column G has several (many) different Book Id's. Those books may have a sub-book in column K. Now column N, has an amount established for each book and sub-book. What I need to do is build a Macro to generate a report that finds the difference between day 1 and day 2 for each book and its sub-book.
Now the tricky part here is that the sub-book in Column K may be used several times in different books from Column G.
What I did was Concatenate all the information in one sheet, build a pivot table and get those differences. But when I try to build the report using a Vlookup and creating a unique identifier I find a dead end since many sub-books are used in different books and regions.
I'm attaching a brief example to show how the data interrelates.
Sheet 1
Sheer2
As you can see Row 2 is in City QN. The Book ID is FLC and Sub-Book TTL555 with 53,000.00. I need to compare this position with the one in sheet 2 (if any) and get the amount difference. Now the thing is that sub-book TTL555 is also used in Row 11 in a different city and under a different book too.
Any ideas?
This is the Code I'm using for the pivot (I don't really need a pivot is just I couldn't figure out another way to do it)
'Create Pivot Table
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim Lastrow As Long
Dim LastCol As Long
'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Differences"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Differences")
Set DSheet = Worksheets("Concatenated")
'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:="Differences")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="StatusReport")
'Insert Data Field
ActiveSheet.PivotTables("SD Differences").AddDataField ActiveSheet.PivotTables( _
"Differences").PivotFields("Qty"), "Sum of Qty", xlSum
'Insert Row Fields
With ActiveSheet.PivotTables("Differences").PivotFields("Book ID")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Differences").PivotFields("Security Code")
.Orientation = xlRowField
.Position = 2
End With
'Insert Column Field
With ActiveSheet.PivotTables("Differences").PivotFields("Position Date")
.Orientation = xlColumnField
.Position = 1
End With
'Add a calculated field to compute variance
With ActiveSheet.PivotTables("Differences").PivotFields("Sum of Qty")
.Calculation = xlDifferenceFrom
.BaseField = "Position Date"
.BaseItem = "(Previous)"
.NumberFormat = "0.00"
.Name = "Position Difference"
End With
'Remove Grand Total
ActiveSheet.PivotTables("Differences").PivotSelect "'Row Grand Total'", _
xlDataAndLabel, True
ActiveSheet.PivotTables("Differences").RowGrand = False
Dim src As Range
Dim ws2 As Worksheet
Set src = Range("B2").CurrentRegion
Set ws2 = ActiveSheet
ws2.ListObjects.Add(SourceType:=xlSrcRange, Source:=src, xlListObjectHasHeaders:=xlYes, tablestyleName:="TableStyleMedium1").Name = "Differences"
Thanks for your help

Runtime error 1004 : Unable to get the PivotTables property of the Worksheet class

I am new to Excel VBA and I am trying to create a pivot table using only Row Field with the following codes but encountered error 1004 and would need help de-bugging.
I've indicated the error occurrence on the codes right after the comments
//
'Macros above create a pivot cache and address to insert the new pivot table
//
for easy referencing.
Appreciate any help on this.
Sub getpivotUI2()
'**strong text**
' getpivotUI2 Macro
' Create PivotTable from Task_Sheet to filter duplicate bill (UI2)
'
Dim P2Sheet, TSheet As Worksheet
Dim P2Cache As PivotCache
Dim P2Table As PivotTable
Dim P2Range As Range
Dim L2Row, L2Col As Long
' Declaring the variables above
Set TSheet = Worksheets("Task_Sheet")
Set P2Sheet = Worksheets("pivot_UI2")
L2Row = TSheet.Cells(Rows.Count, 1).End(xlUp).Row
L2Col = TSheet.Cells(4, Columns.Count).End(xlToLeft).Column
Set P2Range = TSheet.Cells(4, 1).Resize(L2Row, L2Col)
'Macros above determine where the cursor is referenced
P2Sheet.Cells.Delete 'Removing all previous data the pivotTable worksheet
Set P2Cache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=P2Range)
Set P2Table = P2Cache.CreatePivotTable _
(TableDestination:=P2Sheet.Cells(3, 1), TableName:="PivotTableUI2")
'Macros above create a pivot cache and address to insert the new pivot table
With ActiveSheet.PivotTables("PivotTableUI2").PivotFields("UI2") '**<-- ERROR OCCURANCE**
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("Count_UI2")
.Orientation = xlDataField
.Function = xlCount
.Name = "Count of UI2"
End With
With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("R Patient" & Chr(10) & "Count")
.Orientation = xlDataField
.Function = xlCount
.Name = "Count of R Patient"
End With
With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("PR Patient" & Chr(10) & "Count")
.Orientation = xlDataField
.Function = xlCount
.Name = "Count of PR Patient"
End With
'Macros above inserts a row field and data field in the pivot table
End Sub
Try the code below, explanation inside the code's comments
Option Explicit
Sub getpivotUI2()
' getpivotUI2 Macro
' Create PivotTable from Task_Sheet to filter duplicate bill (UI2)
Dim P2Sheet As Worksheet, TSheet As Worksheet
Dim P2Cache As PivotCache
Dim P2Table As PivotTable
Dim P2Range As Range
Dim L2Row As Long, L2Col As Long
' Declaring the variables above
Set TSheet = ThisWorkbook.Worksheets("Task_Sheet")
Set P2Sheet = ThisWorkbook.Worksheets("pivot_UI2")
With TSheet
L2Row = .Cells(.Rows.Count, 1).End(xlUp).Row
L2Col = .Cells(4, .Columns.Count).End(xlToLeft).Column
Set P2Range = .Range(.Cells(4, 1), .Cells(L2Row, L2Col)) ' set the data source of the Pivot-Cache
End With
'Macros above determine where the cursor is referenced
P2Sheet.Cells.Delete 'Removing all previous data the pivotTable worksheet
' set the Pivot-Cache object
Set P2Cache = ActiveWorkbook.PivotCaches.Add(xlDatabase, P2Range.Address(0, 0, xlA1, xlExternal))
' set the Pivot-Table object
Set P2Table = P2Sheet.PivotTables.Add(PivotCache:=P2Cache, TableDestination:=P2Sheet.Range("A3"), TableName:="PivotTableUI2")
'Macros above create a pivot cache and address to insert the new pivot table
' ~~~ For Debug Only ~~~
Dim PTFld As PivotField
For Each PTFld In P2Table.PivotFields
Debug.Print PTFld.Name
Next PTFld
With P2Table.PivotFields("UI2")
.Orientation = xlRowField
.Position = 1
End With
' rest of your Pivot-Fields code ā€¦
End Sub
I've added a section in the Sub above that makes sure your Pivot-Table has a field "U12".
When you run this part:
' ~~~ For Debug Only ~~~
Dim PTFld As PivotField
For Each PTFld In P2Table.PivotFields
Debug.Print PTFld.Name
Next PTFld
You should get the following value in the immediate window:

VBA -Place Pivot Table in Same worksheet

New to VBA and I am having difficulty with my Macro creating a pivot table on the same worksheet with my data (for example, starting the pivot table in the "I1" column). I have been able to run the macro to select all of the data within the sheet and then create this data on another worksheet. Since I will need to loop through a number of worksheets on the same workbook to create multiple pivot tables, having separate sheets isn't feasible.
Each worksheet has the same number of columns with a varying number of rows. My goal is to have this macro look at each worksheet and output a pivot table next to it.
I feel like the macro I have below is not referencing the correct pivot Table destination. Any assistance would be appreciated.
Sub Macro4()
'
'Macro4 Macro
'
'
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
DataSheet & "!R1C1:R" & FinalRow & "C8", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:=DataSheet & "!R1C9", TableName:= _
"PivotTable4", DefaultVersion:=xlPivotTableVersion15
Sheets(DataSheet).Select
Cells(1, 9).Select
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Document Type")
.Orientation = xlRowField.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Accounting Event")
.Orientation = xlRowField.Position = 2
End With
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Document Number")
.Orientation = xlRowField.Position = 3
End With
ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables
( _"PivotTable4").PivotFields("Amount"), "Sum of Amount", xlSum
End Sub
Try the code below, it's with a little different approach, defining Range, PivotTable, PivotCache, and you can modify them easily according to your needs:
Sub Macro4()
Dim FinalRow As Long
Dim DataSheet As String
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim DataRng As Range
Dim TableDest As Range
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
' set data range for Pivot Table
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 8)) ' conversion of R1C1:R & FinalRow & C8
' set range for Pivot table placement
Set TableDest = Sheets(DataSheet).Cells(1, 9) ' 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 = ActiveWorkbook.Sheets(DataSheet).PivotTables("PivotTable4") ' check if "PivotTable4" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' "PivotTable4" doesn't exist >> create it
' create a new Pivot Table in "PivotTable4" sheet
Set PvtTbl = ActiveWorkbook.Sheets(DataSheet).PivotTables.Add(PivotCache:=PvtCache, TableDestination:=TableDest, TableName:="PivotTable4")
With PvtTbl.PivotFields("Document Type")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Accounting Event")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Document Number")
.Orientation = xlRowField
.Position = 3
End With
PvtTbl.AddDataField ActiveSheet.PivotTables( _
"PivotTable4").PivotFields("Amount"), "Sum of Amount", xlSum
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

PivotFields property of the PivotTable Class problems

I know I will be marked down for this but here it goes.
I have been going through several forums and informative websites regarding this error but I just cant work out what is wrong.
The error is:
Run-time error '1004': Unable to get the PivotFields property of the PivotTable Class
This occurs at the line:
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Precinct")
I have seen reference that the error may be because the field is not called "Precinct". However I have copy and pasted it directly and have also ensured that the code "writes" that particular heading. I just can't figure it out. Could it be something to do with refreshing the data or pivot table? Is there a way to replace "Precinct" in the problem line with a cell reference?
The code is:
Sub OccupancyPivot()
Dim SrcData As Variant
Dim LRow As Long, LCol As Long
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
'Determine the data range you want to pivot
LRow = Cells(Rows.Count, 1).End(xlUp).Row
LCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow, LCol).Address(False, False))
Sheets.Add.Name = "PivotTable1"
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
Set PT = PTCache.CreatePivotTable(Sheets("PivotTable1").Range("A1"), "Occupancy")
'Create the headings and row and column orientation
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With Sheets("PivotTable1").PivotTables("Occupancy").PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub
Anyone able to tell me what is wrong with the above?
Edit: I have found a couple of other mentions of this occurring. For some reason when a pivot sub procedure is part of other sub procedures, the pivotfields don't recognize the headings in the data. I am yet to find a definitive reason for this but believe it has something to do with refreshing the pivot and data.
Try the modified code below, I added also cases where you already created the "PivotTable1" sheet and "Occupancy" Pivot table (in previous runs of this code), and then you just want to refresh the Pivot's data with the modified data in "Raw Data" sheet.
Sub OccupancyPivot()
Dim SrcData As Variant
Dim LRow As Long, LCol As Long
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PivotShtExists As Boolean
' Determine the data range you want to pivot
LRow = Worksheets("Raw Data").Cells(Worksheets("Raw Data").Rows.Count, 1).End(xlUp).Row
LCol = Worksheets("Raw Data").Cells(1, Worksheets("Raw Data").Columns.Count).End(xlToLeft).Column
Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow, LCol).Address(False, False))
' check is "PivotTable1" sheet already exists (from previous Macro runs)
For Each wsSheet In ThisWorkbook.Sheets
If wsSheet.Name = "PivotTable1" Then
PivotShtExists = True
End If
Next wsSheet
If Not PivotShtExists Then Sheets.Add.Name = "PivotTable1"
Set wsSheet = ThisWorkbook.Sheets("PivotTable1")
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PT = wsSheet.PivotTables("Occupancy") ' check if "Occupancy" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PT Is Nothing Then
' create a new Pivot Table in "PivotTable1" sheet, start from Cell A1
Set PT = wsSheet.PivotTables.Add(PivotCache:=PTCache, TableDestination:=wsSheet.Range("A1"), TableName:="Occupancy")
'Create the headings and row and column orientation
With PT.PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With PT.PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With PT.PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With PT.PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With PT.PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
Else
' just refresh the Pivot cache with the updated Range (data in Sheet1)
PT.ChangePivotCache PTCache
PT.RefreshTable
End If
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub
After running this code, multiple scanarios, this is the result I am getting (simulated data):
Based on what you've said so far, I think your LRow and/or Lcol variables are being set from the wrong sheet, so your source data isn't what it should be. Try this:
Sub OccupancyPivot()
Dim SrcData As String
Dim wsSheet As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
'Determine the data range you want to pivot
SrcData = "'Raw Data'!" & Worksheets("Raw Data").Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1)
Sheets.Add.Name = "PivotTable1"
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
Set PT = PTCache.CreatePivotTable(Sheets("PivotTable1").Range("A1"), "Occupancy")
'Create the headings and row and column orientation
With PT
With .PivotFields("Precinct")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Registration")
.Orientation = xlDataField
.Function = xlCount
End With
With .PivotFields("Captured Date")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Captured Session")
.Orientation = xlColumnField
.Position = 2
End With
With .PivotFields("Location")
.Orientation = xlRowField
.Position = 2
End With
End With
'ActiveWorkbook.Sheets("PivotTable").Visible = xlSheetVeryHidden
End Sub

Resources