基于值的条件突出显示

conditional highlighting based on values

我已经根据单元格中的关键字定义了一个用颜色填充的范围。目的是突出显示关键字,如下图所示。可以看到 "Auto" 这个词被搜索了,单元格被标记为红色。我被卡住的地方是 "if" 命令的扩展,例如搜索条件在 E 列上进行搜索关键字 "Mortgage"、"Preferred" 和 "non-Preferred" 并在一些标记中标记它颜色。这些关键字始终位于行 "E" 和关键字 "Auto" 旁边的前四列中。问题是 "Mortgage"、"Preferred" 和 "non-Preferred" 这三个关键字并不总是以相同的顺序出现。它可能是 关键字 "preferred" 可能出现在 "Mortgage" 之前。

因此,我的主要问题是 VBA 中是否有一个命令,以便以动态方式突出显示这些关键字,而不使用静态列号,因为这些关键字的顺序可以改变。

 Sub Schaltfläche2_Klicken()
 Dim cell As Range

 For Each cell In ws.Range("A1:A100")
 If cell.Value = "Auto" Then
    Range("A" & cell.Row, "E" & cell.Row, "G" & cell.Row, "I" & cell.Row, "K" & 
cell.Row).Interior.Color = vbRed
ElseIf cell.Value = "Mutti" Then
    Range("A" & cell.Row, "E" & cell.Row, "G" & cell.Row, "I" & cell.Row, "K" & 
cell.Row).Interior.Color = vbRed
End If
Next
End Sub

编辑 在 OP 关于避免白色的评论之后

你可以试试这个(评论中有解释):

Sub Schaltfläche2_Klicken()
    Dim cell As Range, cell2 As Range, col As Long
    Dim ws As Worksheet
    Dim res As Variant

    Set ws = ActiveSheet

    For Each cell In ws.Range("A1:A100").SpecialCells(xlCellTypeConstants) ' loop thorugh column A not empty values
        Select Case cell.Value2 ' check current column A cell value and act accordingly
            Case "Auto"
                col = vbRed
            Case "Mutti"
                col = vbGreen ' change it as per your needs
            Case Else 'if no match
                col = 0
        End Select
        If col > 0 Then ' proceed only if a color has been established
            cell.Interior.Color = col
            For Each cell2 In cell.Offset(, 4).Resize(4).SpecialCells(xlCellTypeConstants)
                res = Switch(cell2.Value = "Mortgage", vbRed, cell2.Value = "Preferred", vbGreen, cell2.Value = "Nonpreferred", vbYellow) ' get color corresponding to cell value (change colors as per your needs)
                If Not IsNull(res) Then Intersect(Range("E:E, G:G, I:I"), Rows(cell2.Row)).Interior.Color = CLng(res) ' if any valid color, apply it
            Next
        End If
    Next
End Sub

参见 here 了解 Switch() 功能

如果您需要不同于 标准 颜色的颜色,您可以使用 RGB() 函数代替