Home » excel » Apply Filter on Excel File – VBA

Apply Filter on Excel File – VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to apply filter to file called “SearchData.xlsx” irrespective of whether file is open or not.

I tried the following code but it gives exception.

Sub ApplyFilterInDataFile()
    IsOpen = False

    For Each wb In Workbooks
        If LCase(wb.Name) = "searchdata.xlsx" Then
            IsOpen = True
        End If
    Next

    If IsOpen Then
        Workbooks("SearchData").ActiveSheet.UsedRange.AutoFilter Field:=42, Criteria1:=Range("SearchName")
    Else
        Set wb = Workbooks.Open(ThisWorkbook.Path & "\SearchData.xlsx")
        Workbooks("SearchData").Activate
        Workbooks("SearchData").ActiveSheet.UsedRange.AutoFilter Field:=42, Criteria1:=Range("SearchName")
        wb.Close SaveChanges:=True
        Set wb = Nothing
    End If
End Sub

I need an expert help please.

How to&Answers:

If the file is saved you have to refer to it with full name including extension:

Workbooks("SearchData.Xlsx").Activate

Answer:

Try this code instead:

Sub ApplyFilterInDataFile()
    Dim IsOpen As Boolean
    Dim wb As Workbook

    Const cStrWBName As String = "SearchData.xlsx"

    On Error Resume Next
    Set wb = Workbooks(cStrWBName)
    On Error GoTo 0

    If wb Is Nothing Then
        IsOpen = True
        Set wb = Workbooks.Open(ThisWorkbook.Path & "\" & cStrWBName)
    End If

    wb.Sheets("YourSheetName").UsedRange.AutoFilter Field:=42, Criteria1:=Range("SearchName")

    If Not IsOpen Then wb.Close SaveChanges:=True

End Sub

Answer:

Try below code :

Sub ApplyFilterInDataFile()

    On Error GoTo err_rout
    Dim wkbPath As String, wb As Workbook, wbkName As String

    wbkName = "SearchData.xlsx"
    wkbPath = ThisWorkbook.Path & "\" & wbkName

    If IsOpen(wkbPath) = False Then Workbooks.Open Filename:=wkbPath

    Set wb = Workbooks(wbkName)
    wb.ActiveSheet.UsedRange.AutoFilter Field:=42, Criteria1:=Range("SearchName")

    wb.Close True
    Set wb = Nothing
    Exit Sub
err_rout:
    MsgBox Err.Description
End Sub

Function IsOpen(strWkbNm As String) As Boolean

    On Error Resume Next

    Dim wBook As Workbook
    Set wBook = Workbooks(strWkbNm)

    If wBook Is Nothing Then    'Not open
        IsOpen = False
        Set wBook = Nothing
        On Error GoTo 0
    Else
        IsOpen = True
        Set wBook = Nothing
        On Error GoTo 0
    End If

End Function