VBA运行时错误445 - Application.FileSearch

问题描述 投票:0回答:1

我和这个链接上的朋友有同样的问题:http://www.vbforums.com/showthread.php?503199-RESOLVED-Opening-an-excel-file-in-VB-without-the-exact-name&highlight=open%20file%20excel

基本上我想打开一个文件,我只知道文件名的一部分,使用VBA-Coding。

我发现上面的网站有潜在的解决方案但不幸的是,我的编译器给了我运行时错误445

Sub openfile()
    Dim i As Integer
    With Application.FileSearch
        'Change the path to your path
        .LookIn = "C:\Temp"
        '* represents wildcard characters
        .FileName = "Sales_Report_1_4_2008*.xls"
        If .Execute > 0 Then 'Workbook exists
            'open all files that find the match
            For i = 1 To .FoundFiles.Count
                Workbooks.Open (.FoundFiles(i))
            Next i
        End If
    End With
End Sub

谁能帮助我让这个代码在Excel 2016上运行?

非常感谢你们

excel vba runtime-error excel-2003
1个回答
0
投票

我认为FileSearch已经停产。可以使用文件系统对象。可以添加对“Microsoft Scripting Runtime”的引用并尝试

Sub openfile()
    Dim Path As String
    Dim FSO As FileSystemObject
    Dim Fl  As File
    Dim Fld As Folder

    Path = "C:\temp\"
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set Fld = oFSO.GetFolder(strPath)

    For Each Fl In Fld.Files
      If Ucase(Fl.Name) Like Ucase("Sales_Report_1_4_2008*.xls") Then
        Workbooks.Open (Fl.Path)
      End If
    Next Fl

    Set FSO = Nothing
    Set Fl = Nothing
    Set Fld = Nothing
End Sub

甚至更简单的循环使用Dir功能

    Sub openfile()
        Dim Path As String
        Dim Fname As String

        Path = "C:\temp\"
        Fname = Dir(Path & "Sales_Report_1_4_2008*.xls")
        Do While Fname <> ""
           Workbooks.Open (Path & Fname)
        Fname = Dir
        Loop

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.