简体   繁体   中英

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. 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?

One option would be to Open the file inside of the FileExists function. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM