Toggle filter on/off using VBA

Jimbob2000

New Member
Joined
Jun 27, 2019
Messages
14
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
 

DanteAmor

Well-known Member
Joined
Dec 3, 2018
Messages
8,974
Office Version
2007
Platform
Windows
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:

DanteAmor

Well-known Member
Joined
Dec 3, 2018
Messages
8,974
Office Version
2007
Platform
Windows
I'm glad to help you. Thanks for the feedback.
 

Forum statistics

Threads
1,082,601
Messages
5,366,571
Members
400,902
Latest member
fathima

Some videos you may like

This Week's Hot Topics

Top