【问题标题】:VBA FIle SearchVBA 文件搜索
【发布时间】:2016-02-13 18:52:52
【问题描述】:
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 文件,但我只知道文件名的一部分,所以请协助我如何打开文件名。谢谢!

【问题讨论】:

标签: excel vba


【解决方案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

【讨论】:

  • 我可以直接打开文件而不搜索吗?
  • @VBA_Coder,如果你不知道文件的全名我认为你不能不搜索就打开它,但是我们可以使用Dir来搜索而不循环(更快),见编辑。
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 2015-03-24
    • 2015-08-04
    • 1970-01-01
    • 2012-04-24
    • 2016-11-13
    • 2015-01-27
    • 1970-01-01
    相关资源
    最近更新 更多