2

如果单元格值大于其他列中的另一个单元格,我需要更改单元格颜色。例如 G6 > D6 中的值,此规则需要适用于整个列。

我用 formatConditions 实现了一些代码,但结果不是很正确。

 Set rngCell = Cells(6, 7)

 Set objCF = rngCell.FormatConditions.Add _
            (Type:=xlCellValue, Operator:=xlGreater, Formula1:=rngCell.offset(, -3))
'set formats for new CF
With objCF
    .Font.ColorIndex = 26
    .Interior.ColorIndex = 19
End With 

使用此代码,我得到的结果规则是:单元格值 > 18(18 是 D6 的单元格值)

但我想要的是这样的规则:单元格值 > $D6

任何人都可以帮忙吗?

4

3 回答 3

1

这是我使用的方法(您可以使用宏记录器轻松创建和修改)。格式将应用于第七列(“G”)。该公式是不言自明的。请注意,由于公式是一个字符串,您可以动态连接列/行。

Dim r As Range

Set r = Sheet1.Columns(7)
r.FormatConditions.Add Type:=xlExpression, Formula1:="=$G1>$D1"
r.FormatConditions(r.FormatConditions.Count).SetFirstPriority
With r.FormatConditions(1)
    .Interior.PatternColorIndex = xlAutomatic
    .Interior.ColorIndex = 19
    .Font.ColorIndex = 26
End With
r.FormatConditions(1).StopIfTrue = False

set r = nothing
于 2012-04-26T17:00:22.680 回答
0

如果您只针对该单元格进行操作,请尝试此操作

Set rngCell = Cells(6, 7)

Set objCF = rngCell.FormatConditions.Add(Type:=xlExpression, _
                                         Operator:=xlGreater, _
                                         Formula1:="=" & rngCell.Address & ">" & rngCell.Offset(, -3).Address)
'set formats for new CF
With objCF
    .Font.ColorIndex = 26
    .Interior.ColorIndex = 19
End With

如果您正在为整个列执行此操作,请尝试此操作

Set rngCell = Cells(1, 7)

Set objCF = Columns("G:G").FormatConditions.Add(Type:=xlExpression, _
                                         Operator:=xlGreater, _
                                         Formula1:="=" & Replace(rngCell.Address, "$", "") & _
                                         ">" & Replace(rngCell.Offset(, -3).Address, "$", ""))
'set formats for new CF
With objCF
    .Font.ColorIndex = 26
    .Interior.ColorIndex = 19
End With
于 2012-04-26T05:52:13.693 回答
0

感谢大家的投入,也许我没有正确描述我的问题。我想要的只是改变G列中一个单元格的颜色,例如值$G$9>$D$9,那么我只需要改变单元格G9的格式,整列的规则相同(不包括四个头排)。

现在我已经制定了一个解决方案,目前它工作正常。

Dim r As Range
Set r = Cells(5, 7)
r.FormatConditions.Delete
r.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=$D5"
r.FormatConditions(r.FormatConditions.Count).SetFirstPriority
With r.FormatConditions(1)
    .Interior.PatternColorIndex = xlAutomatic
    .Interior.ColorIndex = 19
    .Font.ColorIndex = 26
End With
r.FormatConditions(1).StopIfTrue = False

r.Copy
Range("G5:G" & lastRowNum).PasteSpecial xlPasteFormats
于 2012-04-27T04:43:06.317 回答