When I run the below VBA code to create a pivot table, I get an "Invalid procedure or call argument error" when running the macro. The error is on the "Set PT" area.
I've defined worksheet objects but I also tried adjusting the "Table Destination" to directly reference the worksheet and I still get the same error.
Any idea what might be causing the error?
With wsData
Dim PTCache As PivotCache
Dim PT As PivotTable
'Creates the Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=.Range("A1").CurrentRegion)
'Creates pivot table
Set PT = wsPivot.PivotTables.Add( _
PivotCache:=PTCache, _
TableDestination:=wsPivot)
'Defines fields
With PT
.PivotFields("Field 1").Orientation = xlRowField
.PivotFields("Field 2").Orientation = xlRowField
.PivotFields("Field 3").Orientation = xlRowField
.AddDataField .PivotFields("Field 4"), "Field 4", xlCount
.TableStyle2 = "PivotStyleMedium2"
End With
End With
wsPivot?TableDestinationargument requires a specified range. See PivotTables.Add Method