Search code examples
excelvbacolorsrow

VBA color row with specific value/string upto the last column


I would like to color rows with specific cell values (string) in a data set. I have come across the following code which works perfectly with "entire row" but I would like to color the row only up to the last column which contains some value (and there are spaces in between). I have tried to specify the last column and use it with Range to color, but it does not go well with vCell... Thank you for the help!

Sub Highlight()

    Dim vCell As Range
    'Loop through every used cell in the active worksheet
    For Each vCell In ActiveSheet.UsedRange
        If InStr(vCell.Value, "anyword") Then
            vCell.Font.Color = RGB(0, 0, 0)
            vCell.EntireRow.Interior.Color = RGB(204, 255, 204)
        End If
    Next
End Sub

Solution

  • Try below modified sub.

    Sub Highlight()
    Dim vCell As Range
    Dim lastCol As Long
        'Loop through every used cell in the active worksheet
        For Each vCell In ActiveSheet.UsedRange
            If InStr(vCell.Value, "anyword") Then
                vCell.Font.Color = RGB(0, 0, 0)
                lastCol = Cells(vCell.Row, Columns.Count).End(xlToLeft).Column
                Range(Cells(vCell.Row, vCell.Column), Cells(vCell.Row, lastCol)).Interior.Color = RGB(204, 255, 204)
            End If
        Next
    End Sub