在vba中selectPivotItems的问题

我有以下代码循环通过一个范围,并根据范围的值格式化一些PivotItems 。 代码从一张表(带有学生姓名和答案)跳转到另一张表(带有两个RowLabels,QuestionNo和StudentName的透视表),当它find正确的PivotItem时,更改其格式。

 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项目,但它确实存在。

有人可以帮我把debbug的代码?

有人可以帮我把debbug的代码?

如果您可以在wikisend.com上传工作簿样本并在此共享链接,我可以帮助您进行debugging。

我想这是因为没有find学生的东西,但它确实存在。

尝试这个

 student = Trim(ActiveCell.Value) 

此外,您可以重写您的代码,而无需使用.Select和.Activate。 你的代码将运行得更快:)例如( 下面的代码是未经testing的

 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