如果该列中的任何单元格包含红色,则突出显示列标题

时间:2019-03-15 12:42:17

标签: excel vba

我是宏世界的新手,如果该列中的任何单元格包含红色(如果不是),则尝试编写VBA以红色突出显示列标题(第7行是工作表中的列标题)。列标题应突出显示为绿色。我尝试了以下代码,但是将所有列标题突出显示为绿色。

Dim headers As Range, body As Range

Set headers = ActiveSheet.UsedRange.Rows(7).Columns
Set body = ActiveSheet.UsedRange.Offset(1).Columns

For Each body In Range(Range("A11:BD11"), Range("a" & Rows.Count).End(xlUp))
    If body.Interior.Color = vbRed Then
        headers.Interior.Color = IIf(found, vbRed, vbGreen)
    End If
Next

2 个答案:

答案 0 :(得分:0)

尝试一下:

Dim body As Range, ws As Worksheet

Set ws = ThisWorkbook.Sheets("Sheet1") 'Change Sheet1 for the name of the sheet

With ws
    For Each body In .Range(.Range("A11"), .Range("BD" & .Cells(.Rows.Count, 1).End(xlUp).Row)
        If body.Interior.Color = vbRed And _
            Not .Cells(1, body.Column).Interior.Color = IIf(found, vbRed, vbGreen) Then 'To avoid doing it each time a cell on the same colour meets the criteria
            .Cells(1, body.Column).Interior.Color = IIf(found, vbRed, vbGreen)
       End If
    Next
End With

您错误地使用了范围,并且在循环范围时,您之前没有设置变量。它将在For循环中设置

答案 1 :(得分:0)

您可以使用:

Option Explicit

Sub test()

    Dim cell As Range, rng As Range

    With ThisWorkbook.Worksheets("Sheet1")

        'Set the range to loop
        Set rng = .Range("A11:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)

        'Loop range
        For Each cell In rng

            If cell.Interior.Color = vbRed Then
                'If cell interior is red then color Header(Row 7)
                .Cells(7, cell.Column).Interior.Color = vbGreen
                'Exit the loop after the first match
                Exit For
            Else
                'If there is no match leave no fill
                .Cells(7, cell.Column).Interior.ColorIndex = 0
            End If
        Next cell

    End With

End Sub