首页 > 解决方案 > VBA - 删除范围内每个单元格都包含黑色文本的行

问题描述

我的任务是分析一个工作簿,我需要根据文本与行相关的颜色(红色或黑色)来隔离数据。

我基本上需要开发一个宏,它将删除包含范围内“全黑”的数据(文本)的所有行(列 CJ),并保留包含范围内至少一个单元格的所有行(列 CJ)包含“红色”(255,0,0) 的文本。

完成的结果应该是每一行将至少包含一个单元格,其中包含 CJ 列之间的红色文本。

我们的数据设置如下:

名称:

A1,B1

A2,B2 一直到

A2000,B2000

数据(文本)设置如下:

C1 至 J1

C2到J2一路到

C2000、J2000

我发现了许多有条件地颜色格式的代码,但我似乎无法开发出一个能满足我上述要求的代码。

任何帮助将不胜感激。

标签: excelvbacolorsrow

解决方案


您可以使用 AutoFilter 按字体颜色进行过滤。颜色是通过手动格式还是条件格式导出的并不重要。

在您的情况下,您是在许多列中“证明否定”。辅助列似乎是必要的。下面的代码循环遍历列 C:J 并在每次遇到带有红色字体的过滤行时标记“帮助”列。

Sub anyRedFont()

    Dim c As Long

    With Worksheets("sheet1")

        'remove any AutoFilters
        If .AutoFilterMode Then .AutoFilterMode = False

        'insert a 'helper' column and label it
        .Columns("C").Insert
        .Cells(1, "C") = "helper"

        'filter for red font color
        With .Range(Cells(1, "C"), .Cells(.Rows.Count, "K").End(xlUp))

            'cycle through columns looking for red font
            For c = 2 To 9

                'fliter for red font
                .AutoFilter Field:=c, Criteria1:=vbRed, _
                            Operator:=xlFilterFontColor, VisibleDropDown:=False

                'put a value into the 'helper' column
                On Error Resume Next
                With .Resize(.Rows.Count - 1, 1).Offset(1, 0)
                    Debug.Print .SpecialCells(xlCellTypeVisible).Address(0, 0)
                    .SpecialCells(xlCellTypeVisible) = 1
                End With
                On Error GoTo 0

                'remove fliter for red font
                .AutoFilter Field:=c

            Next c

            'fliter for non-blank helper column
            .AutoFilter Field:=1, Criteria1:=1, VisibleDropDown:=False

        End With

        'Do your work with the rows containing at least one cell
        'with red font here

        'remove 'helper' column
        'this removes the AutoFilter since the 'helper' column
        'is the primary filter column at this point
        '.Columns(Application.Match("helper", .Rows(1), 0)).Delete

        'remove AutoFilter (manually with Data, Data Tools, Clear)
        'If .AutoFilterMode Then .AutoFilterMode = False

    End With

End Sub

我已注释掉删除“帮助者”列。“助手”是主要过滤器列,因此删除它也会删除自动过滤器。


推荐阅读