公式中的Excel VBA条件格式公式

我被卡住,我不知道是否有任何解决办法,因为我已经尝试了很多,并一直在失败。

样品

我试图添加一个条件格式,所以B列中的单元格变为黄色,如果它等于或小于A列中的伙伴单元格的19%。所以在上面的例子中,单元格B1应该变成黄色,因为$ 19,000小于或等于到10万美元的19%。

我需要通过excel vba添加这个条件格式。 我尝试添加下面的vba代码,但是B1:B3中的所有单元格的条件格式公式都被$A1*0.19卡住了。 我需要B1条件格式公式为$A1*0.19 ,那么B2条件格式公式将是$A2*0.19等等等等。 我有大约350行的方式不只是3.即使如此,我的vba代码变成$A521325*0.19或者真正的或实际的方式。

 With Sheet1.Range(Sheet1.Cells(1, 2), Sheet1.Cells(3, 2)) daformula = "=$A1*0.19" .FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, Formula1:=daformula .FormatConditions(.FormatConditions.Count).SetFirstPriority .FormatConditions(1).Interior.PatternColorIndex = xlAutomatic .FormatConditions(1).Interior.ThemeColor = xlThemeColorAccent2 .FormatConditions(1).Interior.TintAndShade = -0.249946592608417 .FormatConditions(1).StopIfTrue = False End With 

这个想法是运行macros后,添加条件格式的工作表,当用户更改列B中的一个单元格的颜色要么消失或重新出现,取决于用户更改单元格的值(条件格式必须仍然工作)

您可以创build一个事件来监视列A中的任何更改(将此代码放在Sheet1对象中)

 Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 1 Then 'run code to add conditional formatting condFormat Target End If End Sub 

现在我们只需要改变你的上面的代码来接受目标,并只添加列B中等效单元格的格式

 Public sub condFormat (Target as range) With target.offset(0,1) daformula = "=" & target.address & "*0.19" .FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, _ Formula1:=daformula .FormatConditions(.FormatConditions.Count).SetFirstPriority .FormatConditions(1).Interior.PatternColorIndex = xlAutomatic .FormatConditions(1).Interior.ThemeColor = xlThemeColorAccent2 .FormatConditions(1).Interior.TintAndShade = -0.249946592608417 .FormatConditions(1).StopIfTrue = False End With end sub 

我一次也没有考虑换一个以上的细胞,但这会解决你的挑战

尝试,

 With ActiveSheet.Cells(1, 2).Resize(3, 1) .FormatConditions.Add Type:=xlExpression, Formula1:="=$B1<=($A1*0.19)" .FormatConditions(.FormatConditions.Count).Interior.Color = 65535 End With 

无论你添加诸如.SetFirstPriority还是.StopIfTrue类的.SetFirstPriority ,在.StopIfTrue都取决于其他CF规则如何影响相同的单元格。

从VBA创build条件格式时,与条件格式公式相关的单元格select至关重要。

尝试使用ActiveSheet.cells(1,1).select如果条件格式公式只访问同一行上的值,或者ActiveSheet.cells(2,1)如果它引用上面的行的值。