按列名过滤所有工作表宏

时间:2019-07-09 14:50:07

标签: excel vba

我正在尝试从工作簿的所有工作表中过滤同一列,称为“位置”。过滤器将相同,在这种情况下,选择:“ ABM”,“ AKH”和“ ACH”。 该列不在所有工作表中的同一位置。

我尝试结合一些我在Google上找到的代码,这些代码可以单独工作。但是结合使用时,它仅适用于一张纸。我认为这与停止的“ For”有关。

Sub AllSheetsAutofilter()
    Dim p As Integer, q As Integer
    p = Worksheets.Count
    Dim i As Integer, rngData As Range

    For q = 1 To p
        With Worksheets(q)
            Set rngData = Range("A1")
            i = Application.WorksheetFunction.Match("Location", Range("A1:AZ1"), 0)
            rngData.AutoFilter Field:=i, Criteria1:=Array("ABM", "AC8", "AKH", "ACH", "AC4"), Operator:=xlFilterValues
        End With
    Next q
End Sub

1 个答案:

答案 0 :(得分:1)

你很近。这对我有用:

Sub AllSheetsAutofilter()

    Dim p As Long, q As Long
    p = Worksheets.Count
    Dim i As Long, rngData As Range

    For q = 1 To p
        With Worksheets(q)
            Set rngData = .Cells
            i = Application.WorksheetFunction.Match("Location", .Range("A1:AZ1"), 0)
            rngData.AutoFilter Field:=i, Criteria1:=Array("ABM", "AC8", "AKH", "ACH", "AC4"), Operator:=xlFilterValues
        End With
    Next q

End Sub

请注意使用Long和限定变量。