How do I open a file if I only know part of the file name?

filename*esy is already a "shell ready" wildcard & if thats alway the case you can simply;

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

Just call (or loop until empty) file = Dir$() to get the next match.


There is an Application.FileSearch you can use (see below). You could use that to search for the files that match your pattern. This information taken from 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

Tags:

Excel

Vba