Search code examples
excelvbafor-loop

Coloring Cells via VBA for each loop


My question is now answered. I have selected several cells in excel, e.g. Range("B3:F6"). Running the following code, that I copied from the answer below results in coloring the empty cells grey:

Sub CellColor()
    
Dim cell As Range

For Each cell In Selection.Cells
    If IsEmpty(cell.Value) Then
        cell.Interior.Color = RGB(217, 217, 217)
    End If
Next cell

End Sub

(I have already deleted my false code accidentally.)


Solution

  • Highlight Empty Cells in Range

    A Quick Fix

    Sub CellColor()
        
        Dim cell As Range
        
        For Each cell In Selection.Cells
            If IsEmpty(cell.Value) Then
                cell.Interior.Color = RGB(217, 217, 217)
            End If
        Next cell
        
    End Sub
    

    An Improvement

    Sub HighlightEmpties()
        
        If Selection Is Nothing Then
            MsgBox "Nothing selected.", vbExclamation
            Exit Sub
        End If
        
        If Not TypeOf Selection Is Range Then
            MsgBox "No range selected.", vbExclamation
            Exit Sub
        End If
        
        Dim urg As Range, cell As Range
        
        For Each cell In Selection.Cells
            If IsEmpty(cell.Value) Then
                If urg Is Nothing Then
                    Set urg = cell
                Else
                    Set urg = Union(urg, cell)
                End If
            End If
        Next cell
       
        If urg Is Nothing Then
            MsgBox "No empty cells found.", vbInformation
            Exit Sub
        End If
        
        urg.Interior.Color = RGB(217, 217, 217)
        
    End Sub