[英]Excel VBA - Check if file exists using Wildcard and open the file
I wish to check whether a file exist in a folder on my computer. 我希望检查计算机上的文件夹中是否存在文件。 I have below, which can see if a specific file exists:
我在下面,可以查看是否存在特定文件:
Function FileExists(sFile As String)
sPath = "M:\User\" & sFile & ".xlsm"
FileExists = Dir(sPath) <> ""
End Function
However, my files are named like: Filename - Version xx.xlsm
and is updated regularly. 但是,我的文件命名为:
Filename - Version xx.xlsm
并定期更新。 Please note that there will only be one file in the folder, but the filename can vary. 请注意,文件夹中只有一个文件,但文件名可能会有所不同。
How can I search in the folder using wildcard: 如何使用通配符在文件夹中搜索:
Filename - Version % %
and then, if it find any file, open the file afterwards? Filename - Version % %
,然后找到文件,然后再打开文件吗?
One option would be to Open the file inside of the FileExists
function. 一种选择是在
FileExists
函数内部打开文件。 However, I would not recommend doing this. 但是,我不建议您这样做。 The function should do exactly what the name implies and nothing more.
该函数应该完全按照名称的含义进行操作,仅此而已。
Another option is restructure your code a little bit: 另一个选择是稍微重构代码:
Private Sub OpenFile()
Dim FileName As String
FileName = GetFile("Filename - Version*")
If FileName <> "" Then
'open FileName as needed
End If
End Sub
Private Function GetFile(sFile As String) As String
sPath = "M:\User\" & sFile & ".xlsm"
GetFile = Dir(sPath)
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.