如何使用FormatConditions更改单元格的颜色基于单元格值与其他单元格的比较?

如果单元格的值大于其他列中的另一个单元格,则需要更改单元格颜色。 例如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

任何人都可以帮忙

这是我使用的方法(您可以使用Macro Recorder轻松创build和修改)。 格式将应用于第七列(“G”)。 公式是不言自明的。 请注意,由于公式是一个string,您可以dynamic连接列/行。

 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 

如果你正在做的只是那个单元格然后试试这个

 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 

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

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

 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