条件格式化VBA多个条件

时间:2016-10-24 01:00:15

标签: excel vba excel-vba conditional-formatting multiple-conditions

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

谢谢,

布雷克

1 个答案:

答案 0 :(得分:2)

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