Home » excel » excel – Find cells with yellow color

excel – Find cells with yellow color

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need your assistance with a macro can identify if there is a yellow cells (vbYellow) with certain range

Dim dataset As Range
Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Set dataset = Range(Cells(1, 3), Cells(lastrow, 30))
'I need something like:
if there is vbYellow in Range(Cells(1, 3), Cells(lastrow, 30)) then msgbog "Please correct error"
Else "No error found"
How to&Answers:

Maybe this is what You are looking for:

Sub findyellow()

Dim dataset As Range
Dim lastrow As Long
Dim cell As Range
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Set dataset = Range(Cells(1, 3), Cells(lastrow, 30))

For Each cell In dataset.Cells

    If cell.Interior.Color = vbYellow Then
        MsgBox "Please correct error in cell (" & cell.Row & " " & cell.Column & ")"
        Exit Sub
    End If

Next

MsgBox "No error found"

End Sub

Answer:

Alternatively, if you wouldn’t want to loop potentially (depending on lastrow in column A) thousands of cells, you could try the inbuild SearchFormat and check if there is any cells that are still yellow:

Sub Tst()

Dim rng1 As Range, rng2 As Range, lr As Long
With ThisWorkbook.Sheets("Sheet1")'Change accordingly
    Application.FindFormat.Clear
    Application.FindFormat.Interior.Color = vbYellow
    lr = .Cells(.Rows.Count, "A").End(xlUp).Row
    Set rng1 = .Range(.Cells(1, 3), .Cells(lr, 30))
    Set rng2 = rng1.Find(What:="", SearchFormat:=True)
    If Not rng2 Is Nothing Then
        MsgBox "Please correct error"
    Else
        'All good
    End If
End With

End Sub

.Find() will return Nothing if no cells are found that fullfill the SearchFormat criteria.