【发布时间】:2021-08-29 14:24:06
【问题描述】:
我尝试使用 VBA 创建一些条件格式规则,但我不断收到第三条规则的“下标超出范围”错误。
这是我当前的代码
Dim MyRange As Range
Dim MyRange2 As Range
Dim MyRange3 As Range
'Define the range for the respective rules
Set MyRange = Range("M4:N30")
Set MyRange2 = Range("A4:Z30")
Set MyRange3 = Range("O4:P30")
MyRange2.FormatConditions.Delete
'Rule 1
MyRange.FormatConditions.Add Type:=xlExpression, Formula1:="=$M4<>""NA""", Formula2:="=$N4<>""NA"""
MyRange.FormatConditions(1).Interior.Color = RGB(255, 150, 0)
'Rule 2
MyRange2.FormatConditions.Add Type:=xlExpression, Formula1:="=$O4>56", Formula2:="=$P4>56"
MyRange2.FormatConditions(2).Interior.Color = RGB(255, 255, 0)
'Rule 3
MyRange3.FormatConditions.Add Type:=xlExpression, Formula1:="=$O4<>$P4"
MyRange3.FormatConditions(3).Interior.Color = RGB(255, 255, 0)
如果我将 FormatConditions(3) 中的“3”更改为 1 或 2,则不会出现错误。关于导致错误的原因有什么建议吗?
感谢您的宝贵时间
【问题讨论】:
-
MyRange3似乎是问题所在,而不是规则的数量。 -
FormatConditions.Add返回一个可以直接使用的对象引用,而不是依赖于计数。
标签: excel vba formatting conditional-statements