简体   繁体   中英

How to clear the filter that been set in the vba code?

I have an Excel VBA project to send email out with documents that the user has selected in the Sheet 1. In Sheet 1 there are two columns: Column1 and Column 2. Column2 lists all the documents as hyperlinks, and if the user wants to select a document, he/she puts an "x" in Column1 for the document. Then the user clicks the Send button to send an email. Here is the code for the button click event:

…
    Set Ash = ActiveSheet
    On Error GoTo cleanup

            Ash.Range("A5:B500").AutoFilter Field:=1, Criteria1:="x"

            For Each cell In Ash.Range("B5:B300").SpecialCells(xlCellTypeVisible)
                If cell.Offset(0, -1).Value = "x" Then
                    …
                End If
            Next
…
cleanup:
    Set OutApp = Nothing
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
 …

My problem comes when an error is raised. After the user clicks the Send button, if an error occurs, Sheet1 only has those documents selected, and all the other documents have been filtered out. And there is a filter button showing up on the top of each column, which is fine because I do want the user to be aware of something going wrong.

My problem is that I cannot change the filter settings or back out of the filter. I have to close Excel and then reopen it. Is there any way I could clear the filter by clicking the filter button on top of Column1 and bring all the other documents back?

Something like this?

Sub ToggleAutofilter()
    ' check if autofilter is currently off
    If ActiveSheet.FilterMode = False Then
        ' if it's off, turn it on, and filter on "Nick"
        Range("d5").AutoFilter Field:=1, Criteria1:="Nick"
    Else
        ' if it's on, turn it off
        Range("d5").AutoFilter
    End If
End Sub

See this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM