首页 > 解决方案 > 具有特定值/字符串的 VBA 颜色行直到最后一列

问题描述

我想为数据集中具有特定单元格值(字符串)的行着色。我遇到了以下代码,它与“整行”完美配合,但我想只为包含一些值的最后一列着色该行(并且中间有空格)。我已经尝试指定最后一列并将其与 Range 一起使用来着色,但它与 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

标签: excelvbacolorsrow

解决方案


试试下面的修改子。

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

推荐阅读