VBA 具有特定 value/string 颜色的行直到最后一列

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

我想为数据集中具有特定单元格值(字符串)的行着色。 我遇到了以下代码,它与“整行”完美配合,但我只想为包含一些值的最后一列(并且中间有空格)的行着色。 我试图指定最后一列并将其与 Range to color 一起使用,但它不适用于 vCell ... 感谢您的帮助!

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

尝试下面修改后的子。

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

这是你正在尝试的吗?

Option Explicit

Sub Highlight()
    Dim vCell As Range
    Dim lCol As Long
    Dim ws As Worksheet
    
    '~~> Set this to the relevant worksheet
    Set ws = Sheet1
    
    With ws
        '~~> Loop through every used cell in the active worksheet
        For Each vCell In .UsedRange
            If InStr(vCell.Value, "anyword") Then
                vCell.Font.Color = RGB(0, 0, 0)
                
                '~~> Find last column in that row
                lCol = .Cells(vCell.Row, .Columns.Count).End(xlToLeft).Column
    
                .Range(.Cells(vCell.Row, 1), .Cells(vCell.Row, lCol)).Interior.Color = RGB(204, 255, 204)
            End If
        Next
    End With
End Sub