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

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.
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,880
Messages
6,175,154
Members
452,615
Latest member
bogeys2birdies

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