1

无论文件是否打开,我都想对名为“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

我需要专家帮助。

4

3 回答 3

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
于 2013-03-27T08:23:53.913 回答
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
于 2013-03-27T08:10:06.243 回答
1

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

Workbooks("SearchData.Xlsx").Activate
于 2013-03-27T08:04:33.010 回答