2016-02-13 91 views
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 = F_Name Then 
     GoTo Report 
    End If 
Next 

Report: 
Workbooks.Open Filename:=F_Path & F_Name 

我想打開一個具有相同位置的excel文件,但我只知道文件名的一部分,所以請幫助我如何打開文件名。謝謝!VBA FILE搜索

+0

你必須使用Dir函數通過通配符來打開文件。 http://www.techonthenet.com/excel/formulas/dir.php –

+1

嘗試改變'如果Fl.Name = F_Name然後'爲'如果Fl.Name像F_Name那麼' – Fadi

+0

這個答案將幫助你通過它http://stackoverflow.com/questions/19527415/using-a-wildcard-to-open-an-excel-workbook –

回答

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 
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 
+0

我可以直接打開沒有搜索的文件嗎? –

+0

@VBA_Coder,如果你不知道文件的全名,我不認爲你可以在沒有搜索的情況下打開它,但是我們可以使用'Dir'搜索而不循環(更快),參見編輯。 – Fadi