VBA FIle搜索

时间:2016-02-13 18:52:52

标签: excel excel-vba vba

Sub Main()
Dim FSO As New FileSystemObject
Dim Fl As File
Dim Folder As Folder
Dim F_Name, F_Path As String
F_Path = ThisWorkbook.Path & "\"
Set Folder = FSO.GetFolder(F_Path)
F_Name = "CI*.*"
For Each Fl In Folder.Files
    If Fl.Name = F_Name Then
        GoTo Report
    End If
Next

Report:
Workbooks.Open Filename:=F_Path & F_Name

我想打开一个位置相同的excel文件,但我只知道文件名的一部分,所以请协助我如何打开文件名。谢谢!

2 个答案:

答案 0 :(得分:1)

尝试:

Sub Main()
Dim FSO As New FileSystemObject
Dim Fl As File
Dim Folder As Folder
Dim F_Name, F_Path As String
F_Path = ThisWorkbook.Path & "\"
Set Folder = FSO.GetFolder(F_Path)
F_Name = "CI*.*"
For Each Fl In Folder.Files
    If Fl.Name Like F_Name Then
        GoTo Report
    End If
Next

msgbox "File not found"
exit sub

Report:
Workbooks.Open Filename:=F_Path & Fl.Name
End Sub

修改

使用Dir进行搜索:

Sub TestDir()

    Dim F_Path As String, F_Name As String, f As String

    F_Path = ThisWorkbook.Path & "\"
    F_Name = "CI*.*"

    f = Dir(F_Path & F_Name)

    If f = "" Then
     MsgBox "File not found"
    Else
     Workbooks.Open FileName:=F_Path & f
    End If

End Sub

答案 1 :(得分:0)

Sub Main()
Dim FSO As New FileSystemObject
Dim Fl As File
Dim Folder As Folder
Dim F_Name, F_Path As String
F_Path = ThisWorkbook.Path & "\"
Set Folder = FSO.GetFolder(F_Path)
F_Name = "CI*.*"
For Each Fl In Folder.Files
If Fl.Name Like F_Name Then
    GoTo Report
End If
Next

Report:
Workbooks.Open Filename:=F_Path & Fl.Name