如果条件为真,则搜索行以查找单元格颜色并为给定范围着色

Search row for cell color and color a given range if condition is true

我有一个代码,如果给定范围内的单元格有单词 "Yes",它们将以红色突出显示。由于范围真的很大,如果同一行中的任何单元格填充为红色,我也想在红色列 A 到 I 中添加阴影。这里我留下我的代码。

Sub ChangeColor()
Set MR = Range("A2:CC127")
For Each cell In MR
If cell.Value = "Yes" Then
cell.Interior.ColorIndex = 3
ElseIf cell.Value = "No" Then
cell.Interior.ColorIndex = 15
End If
Next
End Sub

在为单元格着色时,您只需在 A 中的相应单元格中添加一条线来着色

Sub ChangeColor()
    Set MR = Range("A2:CC127")
    For Each cell In MR
    If cell.Value = "Yes" Then
    cell.Interior.ColorIndex = 3
    cells(cell.row,1).Interior.ColorIndex = 3   ' NEW LINE HERE
    ElseIf cell.Value = "No" Then
    cell.Interior.ColorIndex = 15
    End If
    Next
End Sub

您只能处理相关单元格

Sub ChangeColor()
    Dim f As Range
    Dim firstAddress As String

    With Range("A2:CC127") ' reference your range
        Set f = .Find(what:="yes", lookat:=xlWhole, LookIn:=xlValues, MatchCase:=False) ' try and find first cell whose content is "yes"
        If Not f Is Nothing Then ' if  found
            firstAddress = f.Address ' store first found cell address
            Do
                f.Interior.ColorIndex = 3 'color found cell 
                Range("A:I").Rows(f.Row).Interior.ColorIndex = 3 ' color columns A to I cells of the same row of found cell    
                Set f = .FindNext(f) ' try and find next "yes"
            Loop While f.Address <> firstAddress ' stop at wrapping back to first found value
        End If
    End With
End Sub

如您所述,以下代码还将输入范围的整个列着色为浅红色(所有其他列为浅绿色):

Const RNG As String = "B1:L6"

Sub ChangeColor()
    Range(RNG).Interior.Color = RGB(191, 255, 191)
    For Each col In Range(RNG).Columns
        alreadycolored = False
        For Each cel In col.Cells
            If InStr(1, cel.Text, "yes", vbTextCompare) > 0 Then 'found
                If Not alreadycolored Then
                    col.Interior.Color = RGB(255, 191, 191)
                    alreadycolored = True
                End If
                cel.Interior.Color = RGB(127, 0, 0)
            End If
        Next cel
    Next col
End Sub

如有不明之处欢迎追问why/how有效