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

时间:2014-01-15 08:37:52

标签: excel excel-vba excel-2010 vba

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

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

当i = 12并且Case Else, .FormatConditions(i).Font.Color = vbWhite.下发生错误时,它会导致错误。当它发生时,它似乎有点随机,但经常出现在.Font.Color = vbWhite上。如果我只是把它拿出去,那么它有时会消失(显然不是解决方案!)。虽然然后会出现在其他一行中添加格式条件。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我可以建议在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)

祝你好运。