Hi I am totally new to VBA. Currently I am learning how to use vba to create Pivottable and charts. But I am facing the Error 91 problem after debugged my code as below. I am trying to count the number of failpartid occurred at certain time, and then draw the pivottable to show the count number. Thank you!
P.S: So I edited and checked my code again, but found out the "PT is nothing" during debugging. I have dim PT at the beginning, does anybody know why?
With .PivotFields("FailPartId") is the line has the error.
Sub Trial1()
Dim PTCache As PivotCaches
Dim PT As PivotTables
Dim PF As PivotFields
Dim FinalCol As Long
FinalCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
'Range("E1:F1").Select
'Range(Selection, Selection.End(xlDown)).Select
Selection.Name = "PivotData"
Application.Goto Reference:="Trial1"
'Create the Cache
Set PTCaches = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="ActiveSheet!A1")
'Create the pivot table
Set PT = PTCaches.CreatePivotTable(TableDestination:=ActiveSheet.Cells(1, FinalCol + 2), TableName:=”PivotTable1”, ReadData:="PivotData")
'Set the Fields
With PT
'Set column field
With .PivotFields("FailPartId")
.Orientation = xlColumnField
.Position = 1
End With
'Set Row field
With .PivotFields("ProductionYM")
.Orientation = xlRowField
.Position = 1
End With
'Set data feild
ActiveSheet.AddDataField.PivotFields ("FailPartId"), "Count of FailPartId", xlCount
End With
End Sub

MsgBox PT Is Nothingjust beforeWith PT. What you will get?