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

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
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 0
I'm glad to help you. Thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,213,484
Messages
6,113,923
Members
448,533
Latest member
thietbibeboiwasaco

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