在Excel文件上应用筛选器 - VBA

时间:2013-03-27 08:01:32

标签: excel excel-vba autofilter vba

我想将过滤器应用于名为“SearchData.xlsx”的文件,无论文件是否打开。

我尝试了以下代码,但它提供了异常。

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

我需要专家帮助。

3 个答案:

答案 0 :(得分:1)

如果文件已保存,您必须使用全名来引用它,包括扩展名:

Workbooks("SearchData.Xlsx").Activate

答案 1 :(得分:1)

请尝试使用此代码:

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

答案 2 :(得分:1)

尝试以下代码:

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