I have the following code that loops trough a range and formats some PivotItems, according to the value of the range. The code jumps from one sheet (with the students name and answers) to the other (with the pivot table with two RowLabels, QuestionNo and StudentName), and when it finds the correct PivotItem, change its format.
Sub Macro1()
Dim student As String, q1 As String
Dim pt as PivotTable
Worksheets("SheetPivot").Activate
Set pt = ActiveSheet.PivotTables(1)
'Jumps to the Sheet with the range to loop
Worksheets("QuizState").Activate
'Goes to the first value
Range("A1").Select
'Sarts the loop
Do Until IsEmpty(ActiveCell.Value)
'Determines what type of value is.
student = ActiveCell.Value
q1 = ActiveCell.Offset(0,1).Value
If q1 = "WRONG" then
'Jumps to Sheet with PivotTable
Worksheets("SheetPivot").Activate
pt.PivotFields("StudentName").PivotItems(student).LabelRange.Select
Selection.Interior = 65535 'Yellow
Worksheets("QuizState").Activate
End If
ActiveCell.Offset(1,0).Select
Loop
End Sub
Now, for some reason it works sometimes, sometimes it returns a Run-time error '1004': Unable to get the PivotItems property of the PivotField Class which I guess is due to not finding the student item, but it sure is there.
Can someone help me to debbug the code?
I can help you debug it if you can upload a sample of the workbook in wikisend.com and share the link here?
Try this
Also you can rewrite your code without using .Select and .Activate. Your code will run much faster 🙂 For example (THE BELOW CODE IS UNTESTED)