I need to apply the same filter to all the worksheets in the same workbook.
All the sheets have headers in the first row, but the header name that the filter is supp
You are referring always to the ActiveSheet
, whenever you do not specify the worksheet explicitly in your code. Thus, in the Range()
you have to refer to the worksheet like this:
From:
Set rngData = Range("A1").CurrentRegion
count = Application.WorksheetFunction.Match("STATUS", Range("A1:AZ1"), 0)
Change to:
With Worksheets(I)
Set rngData = .Range("A1").CurrentRegion
count = Application.WorksheetFunction.Match("STATUS", .Range("A1:AZ1"), 0)
End With
The dots in the code between With Worksheets(I) - End With
are what makes the difference:
Concerning the Application.WorksheetFunction.Match
, it only matches cells which contain exactly the word "STATUS". If there is something else like a space before or a sign after, then something like this is a good idea:
count = Application.Match("*STATUS*", Worksheets(1).Range("A1:AZ1"), 0)
Then a check is still needed. Like this:
If Not IsError(count) Then
rngData.autofilter Field:=count, Criteria1:="INACTIVE"
End If
Concerning the second part of the question, use *
around the value in the Match function:
Public Sub TestMe()
Range("E1") = "5teSt34"
Debug.Print Application.WorksheetFunction.Match("*Test*", Range("A1:H1"), 0)
End Sub
Will always return 5
.
Basically what you need to do is reference the sheet in your code as you loop through, which you are not doing - you are only referring to the active sheet by not including any references.
With Match you can use wildcards.
Sub WorksheetLoop()
Dim WS_Count As Long
Dim I As Long
WS_Count = ActiveWorkbook.Worksheets.count
Dim count As Variant, rngData As Range
For I = 1 To WS_Count
Set rngData = Worksheets(I).Range("A1").CurrentRegion
count = Application.Match("STATUS", Worksheets(I).Range("A1:AZ1"), 0)
If IsNumeric(count) Then rngData.AutoFilter Field:=count, Criteria1:="INACTIVE"
Next I
End Sub