整个工作表的Excel VBA条件格式

问题描述 投票:0回答:1

我正在尝试找到一种构建VBA代码的方法,该方法会将与预设值匹配的任何单元格转换为颜色。

如果单元格的值为:S-DAYS,C-DAYS,DAYS,它将使单元格为BLUE并带有黑色文本

[E SWING,S-E SWING,C-E SWING它将变成绿色,带有黑色文本

L SWING,S-L SWING,C-L SWING它将变成浅紫色并带有黑色文本

LATES,S-LATES,C-LATES它将变成灰色,带有黑色文本

[AOT将变为黑色,带有黑色文本

VAC,OUT,MIL,TRAIN,它将使单元格变成黑色并带有白色文本

我不确定如何构建此VBA代码,任何帮助都将非常有用。我可以宏记录以下内容,以了解其扩展方式。但是,我不知道如何使其自动应用于工作表,而无需以某种方式进行提示。

Sub DAConditionalFormating()''DAConditionalFormating宏'

'范围(“ D14:XFD999”)。选择

Selection.FormatConditions.Add Type:=xlTextString, String:="DAYS", _
    TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 15773696
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Selection.FormatConditions.Add Type:=xlTextString, String:="E SWING", _
    TextOperator:=xlContains
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:=xlTextString, String:="LATES", _
    TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorDark1
    .TintAndShade = -0.249946592608417
End With
Selection.FormatConditions(1).StopIfTrue = False
Selection.FormatConditions.Add Type:=xlTextString, String:="VAC", _
    TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
    .ThemeColor = xlThemeColorDark1
    .TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorLight1
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False

结束子

vba macros conditional-formatting
1个回答
0
投票

将条件格式应用于整个工作表是一个非常非常糟糕的主意。每当您在工作表中编辑任何单元格时,计算就会开始。

而不是有条件地格式化整个工作表,而使用代码仅格式化刚刚更改的单元格。格式化单元格填充和字体。

在工作表模块的Worksheet_Change事件中运行此代码,并使其在目标单元格上工作。然后它将快速运行,并且仅更改刚刚更改的单元。

这样的事情。根据需要添加更多的ElseIF。代码进入工作表的工作表模块。

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Value = "foo" Then
    With Target.Interior
        .PatternColorIndex = xlAutomatic
        .Color = 15773696
        .TintAndShade = 0
    End With
ElseIf Target.Value = "bar" Then
    With Target.Interior
        .PatternColorIndex = xlAutomatic
        .Color = 5296274
        .TintAndShade = 0
    End With
End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.