Results 1 to 4 of 4

Thread: Toggle filter on/off using VBA

  1. #1
    New Member
    Join Date
    Jun 2019
    Posts
    14
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default Toggle filter on/off using VBA

    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

  2. #2
    Board Regular DanteAmor's Avatar
    Join Date
    Dec 2018
    Location
    México
    Posts
    6,986
    Post Thanks / Like
    Mentioned
    85 Post(s)
    Tagged
    15 Thread(s)

    Default Re: Toggle filter on/off using VBA

    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 by DanteAmor; Oct 21st, 2019 at 07:50 PM.
    Regards Dante Amor

  3. #3
    New Member
    Join Date
    Jun 2019
    Posts
    14
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default Re: Toggle filter on/off using VBA

    Thanks! It worked perfectly!

  4. #4
    Board Regular DanteAmor's Avatar
    Join Date
    Dec 2018
    Location
    México
    Posts
    6,986
    Post Thanks / Like
    Mentioned
    85 Post(s)
    Tagged
    15 Thread(s)

    Default Re: Toggle filter on/off using VBA

    I'm glad to help you. Thanks for the feedback.
    Regards Dante Amor

Some videos you may like

User Tag List

Tags for this Thread

Like this thread? Share it with others

Like this thread? Share it with others

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •