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

问题描述:

如果单元格值大于其他列中的另一个单元格,我需要更改单元格颜色。例如G6> D6中的值,并且此规则需要应用于整个列。如何使用FormatConditions根据单元格值与其他单元格的比较来更改单元格颜色?

我用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

任何人都可以提供帮助吗?

+2

您需要使用Type:= xlExpression。此外,请参阅此链接以解决您可能遇到的问题http://support.microsoft.com/kb/895562 – 2012-04-26 05:50:28

+0

@TimWilliams:对不起,没有看到您的评论。交叉是无意的。 – 2012-04-26 05:52:50

+0

也感谢蒂姆为您的建议,今天没有时间去尝试您的解决方案。我会在稍后尝试。 – 2012-04-26 10:56:59

这是我使用的方法(你可以使用Macro Recorder轻松创建和修改)。格式将应用于第七列(“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 
+0

感谢您的输入,我尝试过,但如果条件为真,则使用此格式的整列将会更改。这不是我所期望的。 – 2012-04-27 04:45:01

+0

我根据您的代码做了一些更新,现在它运行良好。 – 2012-04-27 10:43:44

如果你正在做的,如果仅针对该小区那就试试这个

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 
+0

感谢您的回答,但我仍然在尝试......使用这种方式,我生成的规则类似于:= L1048557> I1048557,我不知道为什么,我想要比较是G和D列。 – 2012-04-26 10:45:53

+0

我是否可以生成如下规则:单元格值> $ D6,然后我可以将此规则应用于所有列,因为如果手动将此规则添加到我的工作表中,效果会很好。 – 2012-04-26 10:48:59

感谢所有的输入,也许我没有正确描述我的问题。我想要的只是改变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