I have decided to attempt a UDF around alternative to Application.FileSearch. I assume a few locations where a file COULD be located. Solutions on the internet tend to assum
You talk about efficiency, do you mean readability? Or efficiency in terms of processing power required? The first example is easy enough to read, and change, so I would say that it's readable, but if you know that a file is in, say, one of 3 locations, it would be better to dir each location separately, as in the second example.
Regarding the following, it relies on the file in question being inside the "HostFolder" that you specify, so effectively the more precise you can be, the more efficient it will be. For example, using the following will be increasingly more efficient:
C:\
C:\Reports
C:\Reports\May
Credit to @Rich for his answer here:
Loop Through All Subfolders Using VBA
Sub MainBeast()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\mypath\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
End Sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
If File.Name = "Name.xlsm" Then
Workbooks.Open (Folder.Path & "\" & "Name.xlsm"), UpdateLinks:=False
Workbooks("Name.xlsm").Activate
Exit Sub
End If
Next
End Sub
I should say though, that this will just open the first instance that it finds of the file named "name.xlsm". You need to make modifications if you want to deal with multiple files, although this should be easily possible by storing the potential paths with the Path.FileDateTime and opening the most recent.
Regarding the second, if you have a shortlist of places to check, then I would use the code below, this is more efficient, but if the file is not in the right location, then it won't work:
sub MainBeast()
if fileExists("C:\" & "Name.xlsm") then Workbooks.Open ("C:\" & "Name.xlsm"), UpdateLinks:=False
if fileExists("C:\locA\" & "Name.xlsm") then Workbooks.Open ("C:\locA\" & "Name.xlsm"), UpdateLinks:=False
if fileExists("C:\locB\" & "Name.xlsm") then Workbooks.Open ("C:\locB\" & "Name.xlsm"), UpdateLinks:=False
End Sub
Function FileExists(ByVal FullPath As String) As Boolean
If dir(FullPath) <> "" Then
FileExists = True
Else
FileExists = False
End If
End Function