【发布时间】:2014-02-03 15:14:29
【问题描述】:
我的代码有时会抛出 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 上。如果我只是简单地 REM 出来,那么它有时会消失(显然不是解决方案!)。虽然随后将出现在其他行之一上,并添加了格式条件。
非常感谢任何帮助。
【问题讨论】:
-
+ 1 用于在解释您的问题时涵盖所有细节 :) 顺便说一句,我对错误消息和您指向的行以及您认为可能发生这种情况的原因感到困惑。当 Excel 无法找到特定对象时,会发生下标超出范围错误。例如
FormatConditions(12)但不是因为vbWhite -
我预计该行会出现更多
'Run-time error '1004:'Application-defined or object-defined error错误... -
在黑暗中拍摄。你能帮我试一试吗?将
.Font.Color = vbWhite更改为.Font.ColorIndex = 2? -
是的 - 它从来没有这样做过 - 总是错误 9。我有很多其他函数可以使用非常相似的方式格式化各种范围,当范围变小时它们往往会排除这个错误大(如超过 9 个项目)。我在输入之前已经删除了所有条件,所以我一辈子都看不到出了什么问题
-
它正在流失 - 将违规行更改为
.font.colorindex = 2并没有帮助,所以我将添加 DoEvents 并看看会导致什么
标签: excel excel-2010 vba