条件格式化VBA多个条件

对于VBA世界来说,我是非常新的,需要一些与条件格式化的VBA方面的帮助。

1)我需要条件格式应用于列(M)

  • 绿色7下
  • 从7-20黄色
  • 红色大于20

最重要的条件是,如果列(N)如果表明NOPO,我不希望应用条件格式。

我已经制定了一个公式来使用,表明需要什么颜色,但无法将其转换为VBA条件格式(此公式显示了什么颜色,是否应该应用条件格式。

=IF(N2="osno",IF(M2<=7,"green",IF(M2<7,IF(M2>20,"red","less than 20"),IF(M2>20,IF(M2>20,"red","less than 20"),"yellow"))),"no format") 

这是我目前的VBA脚本,因为你无疑可以看到它非常混乱,是来自一个录制的脚本。

  Sub Conditional() ' ' Notification_05 Macro ' Conditional Formatting ' ' Sheets("Final").Select Columns("M:M").Select Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _ Formula1:="=8" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .Color = 5296274 .TintAndShade = 0 End With Selection.FormatConditions(1).StopIfTrue = False Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _ Formula1:="=8", Formula2:="=20" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .Color = 49407 .TintAndShade = 0 End With Selection.FormatConditions(1).StopIfTrue = False Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="=20" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .Color = 470000 .TintAndShade = 0 ActiveWindow.SmallScroll Down:=-27 Range("M2").Select With Range("M:M") .FormatConditions.Add Type:=xlExpression, Formula1:= _ "=LEN(TRIM(M1))=0" With .FormatConditions(.FormatConditions.Count) .SetFirstPriority End With End With End With End Sub 

谢谢,

布莱克

CF公式需要返回true或false:不能使用单个公式来分配多种颜色中的一种,只能决定是否应用颜色。 你将需要三条规则,每条规则都有一个稍微不同的公式。

 Sub Tester() Dim rng As Range Set rng = Selection rng.FormatConditions.Delete 'clear any existing rules AddRule rng, "=AND(M2=""osno"", N2<7)", vbGreen AddRule rng, "=AND(M2=""osno"", N2>=7,N2<=20)", vbYellow AddRule rng, "=AND(M2=""osno"", N2>20)", vbRed End Sub 'utility sub: add a CF rule given the formula and a fill color Sub AddRule(rng, sFormula, lColor) With Selection.FormatConditions With .Add(Type:=xlExpression, Formula1:=sFormula) .Interior.Color = lColor .StopIfTrue = True End With End With End Sub