2012-03-07 122 views
1

根據範圍的值,我有以下代碼循環搜索範圍並格式化一些PivotItems。代碼從一張表(帶有學生姓名和答案)跳轉到另一張表(帶有兩個RowLabels,QuestionNo和StudentName的透視表),並且當它找到正確的PivotItem時,更改其格式。在vba中選擇PivotItems的問題

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的代碼?

回答

1

有人能幫我debbug的代碼?

我可以幫你調試它,如果你能在wikisend.com上傳工作簿的樣品,並在這裏分享的鏈接?

我的猜測是由於沒有找到學生的項目,但它肯定是存在的。

試試這個

student = Trim(ActiveCell.Value) 

你也可以重寫代碼,而無需使用。選擇和.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 
+0

這確實是做什麼,我需要的。出於某種原因,我寫的代碼找到了Pivot Item,但並沒有在所有情況下選擇它(名稱已被修剪)。繞過選擇,代碼就像一個魅力。非常感謝。 – Pragabhava 2012-03-09 02:07:16