如何在Excel VBA宏中进行条件格式化?

时间:2012-09-07 09:43:09

标签: vba

我使用下面的代码在excel单元格中插入条件格式。

range("d" & rowno).Select
Selection.Offset(1, 0).EntireRow.Insert
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="= RC > 7"
Selection.FormatConditions(Selection.FormatConditions.count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 65535 'Yellow
    .TintAndShade = 0
End With

通过比较“7”定义的更大的值,上述工作正常... 但是,如果我传递变量“lhigh”,其中存储了值,并且同样的im在表格中传递它不起作用。 例如;     lhigh=7

range("d" & rowno).Select
Selection.Offset(1, 0).EntireRow.Insert
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="= RC > lhigh"
Selection.FormatConditions(Selection.FormatConditions.count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 65535 'Yellow
    .TintAndShade = 0
End With

请告诉我们如何计算大于检查是否传递变量而不是直接整数值

2 个答案:

答案 0 :(得分:2)

你需要这个:

Formula1:="= RC > " & lhigh

即。你需要使用&运算符进行字符串连接。

然后

"= RC > " & lhigh将评估为"= RC > 7"

答案 1 :(得分:2)

如果我将单元格命名为“Arc”而另一个单元格命名为“lhigh”,则以下子项在Excel 2007中为我工作

Sub test()

Dim foo As Range

Set foo = ActiveWorkbook.Sheets("Sheet1").Range("C3")

With foo.FormatConditions _
        .Add(xlExpression, Formula1:="=Arc>lhigh")

    With .Font
        .Bold = True
        .ColorIndex = 4
    End With
End With

End Sub

这将在单元格C3上设置条件格式,当Arc中的值为>时,它将启动。 lhigh。

也许您应该将代码简化为类似这样的基础,然后添加额外的复杂性。我猜你的问题出在代码的另一部分。

相关问题