VBA设置格式条件时出错
首先,代码如下:主要是要实现在第二行里加一个格式条件判断,如果A2="BAD", 则B2:AE2显示红色,或A2="OK",则显示黑色字体,或A2="SKIP",显示灰色字体。其次,如果直接运行代码,没有任何异常。但是如果回到excel里面操作一下,比如设置一个cell值,然后再回到代码编辑窗口Alt+F11, 再次运行,就会出现问题,格式的条件就变成了"OR($A1048559="BAD", $A1048559="TOBE")",而不是正确的”=OR($A2="BAD", $A2="TOBE")“。见下面的debug信息。请问大侠这是怎么回事。
Sub ccc()
i = 2
With Range("B" & i & ":AE" & i)
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=OR($A" & i & "=""BAD"", $A" & i & "=""TOBE"")"
.FormatConditions(1).Font.ColorIndex = 3
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A" & i & "=""SKIP"""
.FormatConditions(2).Font.ColorIndex = 15
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A" & i & "=""OK"""
.FormatConditions(3).Font.ColorIndex = 1
.Font.Bold = True
End With
Debug.Print Now & " After" & "£º" & Cells(2, 2).FormatConditions.Item(1).Formula1
End Sub
debug 信息
2012/6/10 0:54:56 After£º=OR($A2="BAD", $A2="TOBE")
2012/6/10 0:55:01 After£º=OR($A2="BAD", $A2="TOBE")
2012/6/10 0:55:06 After£º=OR($A2="BAD", $A2="TOBE")
2012/6/10 0:55:25 After£º=OR($A1048559="BAD", $A1048559="TOBE") --------------------编程问答-------------------- 问题可能出现在 i 将变量i 变成长变量 可能是命名冲突
isskdfjsldfkjsdf= 2 --------------------编程问答-------------------- Sub ccc()
dim i
i = 2
With Range("B" & i & ":AE" & i)
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=OR($A" & i & "=""BAD"", $A" & i & "=""TOBE"")"
.FormatConditions(1).Font.ColorIndex = 3
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A" & i & "=""SKIP"""
.FormatConditions(2).Font.ColorIndex = 15
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A" & i & "=""OK"""
.FormatConditions(3).Font.ColorIndex = 1
.Font.Bold = True
End With
Debug.Print Now & " After" & "£º" & Cells(2, 2).FormatConditions.Item(1).Formula1
End Sub
或者加上变量声明来确认作用域 --------------------编程问答--------------------
谢谢二楼的回复,不过我试了加上i的变量声明,还是没用,仍然出现
2012/6/10 0:55:25 After£º=OR($A1048559="BAD", $A1048559="TOBE")
而且“1048559”出的很奇怪,这个明显已经溢出excel的单元格了。 --------------------编程问答-------------------- 同样问题,我用Ruby调Excel
new_sheet.range("A3:#{str1}#{2 + content.size}").formatconditions.add :type => 2, :formula1 => "= A3 <> #{next_str(next_str str1)}3"
代码里hardcode的A3,跑到实际的公式里就莫名其妙变掉了,很不理解…… --------------------编程问答-------------------- 楼主我知道了,在FormatConditions.Add之前,一定要把Range select,即先Range.Select,然后再Range.FormatConditions.Add,你可以试一下! --------------------编程问答--------------------
补充:VB , VBA