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.
msgbox PT.PivotFields("Precinct").Caption
return if you add it before the line causing the error? – Rory