2014-01-15 93 views
2

我的代碼有時會拋出一個Error 9, Subscript out of range錯誤。在許多其他事情中,我的代碼會佔用大量的單元格,並將現有的條件格式化移除給它們,然後重新應用它,並在i條件中添加數量,這取決於剛添加到某個範圍的項目數量。下標超出範圍錯誤(錯誤9):.FormatConditions

Function FormatLevelX() 
Dim i As Integer 
Dim j As Integer 
Dim k As Integer 
Dim r As Integer 
Dim sLevelRangeName As String 
For j = 1 To Sheets("LEVEL").Range("MajorLevels").Columns.Count 'repeat this for each of the major levels 
    sLevelRangeName = "Level" & Sheets("LEVEL").Range("MajorLevels").Cells(1, j) 
    For k = 1 To Sheets("LEVEL").Range(sLevelRangeName).Columns.Count 'repeat this for each column per major level 
     For r = 2 To 5 'repeat this for each of the 4 cells (each on a different row) in the column that need conditional formatting 
      With Sheets("LEVEL").Range(sLevelRangeName).Cells(r, k) 
        .FormatConditions.Delete 
        .Validation.Delete 
       For i = 1 To Sheets("Level").Range("MajorLevels").Columns.Count 'make one rule per major level 
        .FormatConditions.Add Type:=xlExpression, Operator:=xlEqual, Formula1:="=MATCH(" & ColLett(Range(sLevelRangeName).Cells(2, k).Column) & "2,MajorLevels,0)=" & i 
         Select Case (i) 
         Case 1, 2, 3, 4, 5 
          .FormatConditions(i).Interior.ColorIndex = 45 + i 
          .FormatConditions(i).Font.Color = vbWhite 
          .FormatConditions(i).NumberFormat = "@" 
         Case 6 
          .FormatConditions(i).Interior.ColorIndex = 23 
          .FormatConditions(i).Font.Color = vbWhite 
          .FormatConditions(i).NumberFormat = "@" 
         Case 7, 8, 9 
          .FormatConditions(i).Interior.ColorIndex = 45 + i + 1 
          .FormatConditions(i).Font.Color = vbWhite 
          .FormatConditions(i).NumberFormat = "@" 
         Case Else 
          .FormatConditions(i).Interior.ColorIndex = 9 + i - 10 
          .FormatConditions(i).Font.Color = vbWhite 
          .FormatConditions(i).NumberFormat = "@" 
         End Select 
       Next i 
      End With 
     Next r 
    Next k 
Next j 

End Function 

在那一刻,我= 12,下Case Else, .FormatConditions(i).Font.Color = vbWhite.看起來有點隨機它發生時,作爲發生錯誤,但經常發生在.Font.Color = vbWhite它導致錯誤。如果我簡單地將其解決,那麼它有時會消失(顯然不是解決方案!)。雖然會出現在添加了格式條件的其他行之一上。

任何幫助極大的讚賞。

+1

+ 1,用於覆蓋每一個細節,同時解釋您的問題,爲什麼你認爲這可能發生:) BTW我是那種與錯誤信息,您都指向線和原因的困惑。下標超出範圍錯誤發生在Excel無法找到特定對象時。例如'FormatConditions(12)',但不是因爲'vbWhite' –

+0

我期望更多的'運行時錯誤'1004:'該應用程序定義或對象定義的錯誤'錯誤... –

+0

A在黑暗中射擊。你能爲我做點什麼嗎?將'.Font.Color = vbWhite'改爲'.Font.ColorIndex = 2'? –

回答

0

可能,我建議再下面的變化對newFC斷點,以確定它的內容:

昏暗newFC作爲FormatCondition 集newFC = .FormatConditions.Add(類型:= xlExpression,運營商:= xlEqual,一級方程式:=」 = MATCH(」 & COLLETT(範圍(sLevelRangeName).Cells(2,k)的.COLUMN)& 「2,MajorLevels,0)=」 &ⅰ)

好運。

+0

謝謝。我沒有實施你的建議,但找出發生了什麼問題是一件好事。非常奇怪的是,當我刪除formatCondition被設置爲vbWhite時,問題得到解決。問題就會消失。它遍佈我的代碼(擁有大約10,000行代碼),並且在任何地方它都會出現,它總是將FormatCondition設置爲vbWhite。我刪除了那行代碼,一切都很好。誰知道爲什麼 - 希望這個「發現」能夠幫助其他人。謝謝你所有的提示 – user3197246