下标超出范围错误(错误9):.FormatConditions

我的代码有时会抛出Error 9, Subscript out of range错误。 在许多其他的事情中,我的代码需要大量的单元格,并删除现有的条件格式,然后重新应用它添加在一些条件取决于刚刚添加到一个范围的项目数。

 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 。 如果我简单地把它解决掉,那么它有时会消失(显然不是解决scheme!)。 虽然会出现在格式条件被添加的其他行之一。

任何帮助极大的赞赏。

我可以build议下面的更改,然后在newFC断点确定它的内容:

Dim newFC As FormatCondition set newFC = .FormatConditions.Add(Type:= xlExpression,Operator:= xlEqual,Formula1:=“= MATCH(”&ColLett(Range(sLevelRangeName).Cells(2,k).Column)&“2 ,MajorLevels,0)=“&i)

祝你好运。