简体   繁体   English

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

[英]How to Apply Conditional Formatting to Columns Based on Cell Value

in the following VBA-Code i'm trying to give the Cells in Range("H1:IV1") different colors based on the content of the Cell在下面的 VBA 代码中,我试图根据单元格的内容为 Range("H1:IV1") 中的单元格提供不同的 colors

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

my questions are:我的问题是:

1- How can i set the Variable "SrchRng" to search in first Row not just in Range("H1:IV1")? 1-如何设置变量“SrchRng”以在第一行搜索,而不仅仅是在 Range(“H1:IV1”) 中?

2- The changing color Code works good on the cell but i need to apply the color on the Column where the if-statement true. 2-更改颜色代码在单元格上效果很好,但我需要在 if 语句为真的列上应用颜色。

Please, test the next code:请测试下一个代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM