Hi, I have a VBA/macro code here which autofilters the values in activesheet. My aim is to actually make the VBA code run for the sheets i specify.
Aim: When i press the form button it should filter the values in both the sheets and not just active sheet.
The methods i tried are not working, it would be really helpful if someone could help. Here is the code i have been using.
Sheets i want it to run on : "Prev Month" and "Current Month"
Sub Macro1()'' Macro1 Macro''Dim xWs As Worksheet Dim rng As Range, res As VariantIf xWs.Name <> "Prev Month" And xWs.Name <> "Current Month" ThenRange("A1").SelectSelection.AutoFilterSet rng = Worksheet.AutoFilter.Range.Rows(1)res = Application.Match("Diaper Range Premium (1) Mainline (2)", rng, 0)rng.AutoFilter Field:=res, Criteria1:="MAINLINE"Dim rng1 As Range, res1 As VariantSet rng1 = Worksheet.AutoFilter.Range.Rows(1)res1 = Application.Match("Diaper Type (1) - Taped (2) - Pants (9) - Unspecified", rng1, 0)rng1.AutoFilter Field:=res1, Criteria1:="PANTS"End IfEnd Sub
The statement If xWs.Name <> "Prev Month" And xWs.Name <> "Current Month" Then is not doing what you are trying to do.
It should be If xWs.Name = "Prev Month" OR xWs.Name = "Current Month" Then
The following code will work on a sheet if it's name is either Prev Month or Current Month.
Sub Macro1()Dim xWs As WorksheetDim rng As Range, res As VariantFor Each xWs In Worksheets If xWs.Name = "Prev Month" Or xWs.Name = "Current Month" Then xWs.AutoFilterMode = False With xWs.Rows(1) Set rng = xWs.Rows(1) res = Application.Match("Diaper Range Premium (1) Mainline (2)", rng, 0) .AutoFilter Field:=res, Criteria1:="MAINLINE" res = Application.Match("Diaper Type (1) - Taped (2) - Pants (9) - Unspecified", rng, 0) .AutoFilter Field:=res, Criteria1:="PANTS" End With End IfNext xWsEnd Sub
It should be If xWs.Name = "Prev Month" OR xWs.Name = "Current Month" Then
The following code will work on a sheet if it's name is either Prev Month or Current Month.
Open in new window