如何根据单元格值将条件格式应用于列

How to Apply Conditional Formatting to Columns Based on Cell Value

在下面的 VBA-代码中,我试图根据单元格的内容为范围 ("H1:IV1") 中的单元格赋予不同的颜色

Sub AddColor()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("H1:IV1")

For Each cel In SrchRng
    If InStr(1, cel.Value, "|unsichtbar|") > 0 Then
        cel.Interior.Color = vbRed
    End If
    If InStr(1, cel.Value, "|lesen|") > 0 Then
        cel.Interior.Color = vbYellow
    End If
    If InStr(1, cel.Value, "|schreiben|") > 0 Then
        cel.Interior.Color = vbGreen
    End If
Next cel

End Sub

我的问题是:

1- 我如何将变量“SrchRng”设置为在第一行中搜索而不仅仅是在范围 ("H1:IV1") 中搜索?

2- 更改颜色代码在单元格上效果很好,但我需要在 if 语句为真的列上应用颜色。

请测试下一个代码:

Sub AddColor()
 Dim SrchRng As Range, cel As Range, sh As Worksheet
 Dim lastCol As Long, lastR As Long

 Set sh = ActiveSheet      'use here the needed sheet
 lastCol = sh.cells(1, Columns.count).End(xlToLeft).Column 'last column
 lastR = sh.UsedRange.rows.count                           'last row

 Set SrchRng = sh.Range("A1", sh.cells(1, lastCol)) 'the range to be searched

 For Each cel In SrchRng
    If InStr(1, cel.Value, "|unsichtbar|") > 0 Then
        sh.Range(cel, sh.cells(lastR, cel.Column)).Interior.Color = vbRed
    ElseIf InStr(1, cel.Value, "|lesen|") > 0 Then
        sh.Range(cel, sh.cells(lastR, cel.Column)).Interior.Color = vbYellow
    ElseIf InStr(1, cel.Value, "|schreiben|") > 0 Then
        sh.Range(cel, sh.cells(lastR, cel.Column)).Interior.Color = vbGreen
    End If
 Next cel
End Sub