搜索行以查找单元格颜色,并在条件为真时给定范围内的颜色

时间:2018-07-12 10:49:08

标签: excel vba excel-vba fill

我有一个代码,其中如果给定范围内的单元格带有单词“是”,则它们会以红色突出显示。由于范围确实很大,如果同一行中的任何单元格都用红色填充,我也想在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

3 个答案:

答案 0 :(得分:1)

在为单元格着色时,您只需添加一行即可为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

答案 1 :(得分:0)

您只能处理相关单元格

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

答案 2 :(得分:0)

下面的代码还将输入范围的整个列用浅红色(其他所有颜色都用浅绿色)着色:

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

请随时询问是否不清楚其作用/方式。