我的代碼有時會拋出一個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,用於覆蓋每一個細節,同時解釋您的問題,爲什麼你認爲這可能發生:) BTW我是那種與錯誤信息,您都指向線和原因的困惑。下標超出範圍錯誤發生在Excel無法找到特定對象時。例如'FormatConditions(12)',但不是因爲'vbWhite' –
我期望更多的'運行時錯誤'1004:'該應用程序定義或對象定義的錯誤'錯誤... –
A在黑暗中射擊。你能爲我做點什麼嗎?將'.Font.Color = vbWhite'改爲'.Font.ColorIndex = 2'? –