根据单元格颜色过滤

时间:2019-09-23 10:47:45

标签: excel vba filter

我正在尝试在Excel中编写宏。

我有多张纸,我想根据填充颜色进行过滤。

如何为此编写宏?使用“录制宏”按钮录制了一个宏,但这仅适用于一张纸。这就是我自己做的所有事情。如何将该MACRO应用于所有工作表?我的代码如下:

Sub FILTER_MACRO()
'
' FILTER_MACRO Macro
 '
    ActiveSheet.Range("$A$1:$C$17").AutoFilter Field:=2, Criteria1:=RGB(255, _
        255, 0), Operator:=xlFilterCellColor
End Sub

1 个答案:

答案 0 :(得分:0)

Public Sub Filter_Macro()

    Dim wrkSht As Worksheet

    'Loop through all sheets in the workbook containing the code (ThisWorkbook).
    For Each wrkSht In ThisWorkbook.Worksheets

        'With...End With block.
        '".Range", ".Cells" will refer to wrksht due to this block.
        '".Cells(.Rows.Count, 3).End(xlUp)" will find the last row containing data in column C.
        With wrkSht
            .Range(.Cells(1, 1), .Cells(.Rows.Count, 3).End(xlUp)).AutoFilter _
                Field:=2, Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor

            'Original filter range.
            '.Range("$A$1:$C$17").AutoFilter _
                Field:=2, Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor

            'Using last row containing data in column A.
            '.Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 3)).AutoFilter _
                Field:=2, Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor

        End With

    Next wrkSht

End Sub  

进一步阅读:
With....End With
For Each...Next
Range.End Property