我需要打开一个我不知道的完整文件名的文件。
我知道文件名是这样的。
filename*esy
我肯定知道在给定目录中只出现过一次此文件。
答案 0 :(得分:17)
filename*esy
已经是“shell ready”通配符&如果总是如此,你可以简单地说;
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$()
即可获得下一场比赛。
答案 1 :(得分:2)
您可以使用Application.FileSearch
(见下文)。您可以使用它来搜索与您的模式匹配的文件。此信息取自here。
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
答案 2 :(得分:1)
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
答案 3 :(得分:0)
我正在尝试将此问题作为一项功能。这是最终为我工作的解决方案。
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
这对我来说可以作为单个或数组函数使用。
答案 4 :(得分:0)
如果您知道没有其他文件包含&#34; filename&#34;和&#34; esy&#34;按此顺序,你可以简单地使用
Workbooks.Open Filename:= "Filepath\filename*esy.*"
或者如果您知道丢失字符的数量(假设4个字符未知)
Workbooks.Open Filename:= "Filepath\filename????esy.*"
我使用此方法在日期和文件的文件上运行代码加盖时间戳以忽略时间戳部分。