vba:如果我只知道文件名的一部分,我该如何打开一个文件?
我需要打开一个完整的文件名我不知道的文件。
我知道文件名是类似的。
filename*esy
我知道这个文件在给定目录中只有一个出现。
filename*esy
已经是一个“shell准备”通配符,如果这样的话filename*esy
你可以简单地;
const SOME_PATH as string = "c:\rootdir\" ... Dim file As String file = Dir$(SOME_PATH & "filename*esy" & ".*") If (Len(file) > 0) Then MsgBox "found " & file End If
只要调用(或循环直到空) file = Dir$()
来获得下一场比赛。
有一个Application.FileSearch
你可以使用(见下文)。 您可以使用它来search符合您的模式的文件。 这个信息取自这里 。
Sub App_FileSearch_Example() With Application.FileSearch .NewSearch .LookIn = "c:\some_folder\" .FileName = "filename*esy" If .Execute(SortBy:=msoSortByLastModified, SortOrder:=msoSortOrderDescending) > 0 Then For i1 = 1 To .FoundFiles.Count ' do something with matched file(s) Next i1 End If End With End Sub
If InStr(sFilename, "filename") > 0 and InStr(sFilename, "esy") > 0 Then 'do somthing end if
或者你可以使用RegEx
Dim RE As Object, REMatches As Object Set RE = CreateObject("vbscript.regexp") With RE .MultiLine = False .Global = False .IgnoreCase = True .Pattern = "filename(.*)esy" End With Set REMatches = RE.Execute(sFilename) REMatches(0) 'find match
我正在尝试这个问题的function。 这是最终为我工作的解决scheme。
Function fileName(path As String, sName As String, ext As String) As Variant 'path is Full path from root. Can also use path = ActiveWorkbook.path & "\" 'sName is the string to search. ? and * are wildcards. ? is for single char 'example sName = "book?" or sName ="March_*_2014*" 'ext is file extention ie .pdf .xlsm .xls? .j* Dim file As Variant 'Store the next result of Dir Dim fname() As String 'Dynamic Array for result set ReDim fname(0 To 0) Dim i As Integer ' Counter i = 0 ' Use dir to search and store first result fname(i) = path & Dir(path & "\" & sName & ext) i = i + 1 'Load next result file = Dir While file <> "" 'While a file is found store that file in the array ReDim Preserve fname(0 To i) As String fname(i) = path & file file = Dir Wend fileName = Application.Transpose(fname) 'Print out array End Function
这适用于我作为单个或数组函数。
如果你知道没有其他文件包含“文件名”和“艾西”的顺序,那么你可以简单地使用
Workbooks.Open Filename:= "Filepath\filename*esy.*"
或者,如果你知道缺less的字符数(然后假设4个字符未知)
Workbooks.Open Filename:= "Filepath\filename????esy.*"
我使用这种方法来运行date和时间戳的文件上的代码来忽略时间戳部分。