Toggle filter on/off using VBA

Jimbob2000

New Member
Joined
Jun 27, 2019
Messages
25
I have some pretty simple code that just isn't working... Basically, I want to create a button at the head of a column to toggle a filter on and off. So, if I click the button when the filter isn't applied, it applies the filter; if I click the button when it is applied, the filter is removed.

When I run the macro, the filter applies for a split second then is taken off. I can't work out what's going on. I'm pretty new to using If statements, so maybe that's where I'm going wrong...?



Code:
Sub S12()

With ActiveSheet


If .Range("A2:AF5000").AutoFilter(field:=17, Criteria1:="x") = False Then
    .Range("A2:AF5000").AutoFilter field:=17, Criteria1:="x"
Else: .Range("A2:AF5000").AutoFilter field:=17
    
End If
End With


End Sub
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
Try this

Code:
Sub S12()
  With ActiveSheet
    If .AutoFilter.Filters.Item(17).On Then
      .Range("A2:AF5000").AutoFilter Field:=17
    Else
      .Range("A2:AF5000").AutoFilter Field:=17, Criteria1:="x"
    End If
  End With
End Sub
 
Last edited:
Upvote 1

Forum statistics

Threads
1,223,214
Messages
6,170,771
Members
452,353
Latest member
strainu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top