根据范围的值,我有以下代码循环到一个范围并格式化一些PivotItems
。代码从一个工作表(带有学生姓名和答案)跳转到另一个工作表(带有两个RowLabel,QuestionNo和StudentName的数据透视表),当它找到正确的数据透视表时,更改其格式。
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
现在,由于某种原因,它有时会起作用,有时会返回Run-time error '1004': Unable to get the PivotItems property of the PivotField Class
,我猜这是因为找不到student
项目,但确实存在。
有人可以帮我解读代码吗?
答案 0 :(得分:1)
有人可以帮我解读代码吗?
如果您可以在wikisend.com上传工作簿样本并在此处分享链接,我可以帮您调试吗?
我猜是因为找不到学生用品,但确实存在。
试试这个
student = Trim(ActiveCell.Value)
此外,您可以在不使用.Select和.Activate的情况下重写代码。您的代码将运行得更快:)例如(以下代码未经测试)
Sub Macro1()
Dim student As String, q1 As String
Dim pt As PivotTable
Dim ws1 As Worksheet, ws2 As Worksheet
Dim ws2LastRow As Long, i As Long
Set ws1 = Worksheets("SheetPivot")
Set pt = ws1.PivotTables(1)
Set ws2 = Worksheets("QuizState")
With ws2
ws2LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To ws2LastRow
'Determines what type of value is.
student = Trim(.Range("A" & i).Value)
q1 = UCase(Trim(.Range("B" & i).Value))
If q1 = "WRONG" Then
'Jumps to Sheet with PivotTable
pt.PivotFields("StudentName").PivotItems(student).LabelRange.Interior = 65535 'Yellow
End If
Next
End With
End Sub