Public Sub Excelquestion55()
Const SEARCHFOLDER As String = "C:\Users\Excelquestion55\documents" ' <<<<<<<< change to suit
Const SEARCHFORINFILENAME As String = "563412" ' <<<<<<<< change to suit
Dim oDict As Object, FullName As String, FileDate As Date
Set oDict = CreateObject("Scripting.Dictionary")
GetFiles SEARCHFOLDER, "*" & SEARCHFORINFILENAME & "*.xls?", oDict
If Not oDict.Count = 0 Then
DictSortByValue oDict, xlDescending
FullName = oDict.Keys()(0)
FileDate = oDict.Items()(0)
MsgBox "This file is about to be opened:" & vbNewLine & FullName & vbNewLine & "last modified on " & FileDate, vbInformation
Application.Workbooks.Open FullName
Else
MsgBox "Couldn't find any filename containing: " & vbNewLine & SEARCHFORINFILENAME & vbNewLine & _
"within folder: " & vbNewLine & _
SEARCHFOLDER & vbNewLine & "or its subfolders."
End If
Set oDict = Nothing
End Sub
Public Sub GetFiles(ByVal argSourcePath As String, ByVal argFileSpec As String, ByRef argDictionary As Object)
Dim FSO As Object, oRoot As Object, oFile As Object, oFolder As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(argSourcePath) And Not argFileSpec = vbNullString And Not argDictionary Is Nothing Then
Set oRoot = FSO.GetFolder(argSourcePath)
For Each oFile In oRoot.Files
If oFile.Name Like argFileSpec Then
argDictionary.Add oFile.Path, oFile.DateLastModified
End If
Next oFile
For Each oFolder In oRoot.SubFolders
Call GetFiles(oFolder.Path, argFileSpec, argDictionary)
Next oFolder
End If
End Sub
Public Sub DictSortByValue(ByRef argDict As Object, Optional ByVal argSortOrder As XlSortOrder = xlAscending)
Dim arrList As Object, dictTmp As Object
Dim coll As Collection
Dim vKey As Variant, vValue As Variant, vItem As Variant
Set arrList = CreateObject("System.Collections.ArrayList")
Set dictTmp = CreateObject("Scripting.Dictionary")
On Error GoTo SUB_ERROR
For Each vKey In argDict
vValue = argDict(vKey)
If Not dictTmp.Exists(vValue) Then
Set coll = New Collection
dictTmp.Add vValue, coll
arrList.Add vValue
End If
dictTmp(vValue).Add vKey
Next vKey
arrList.Sort
If argSortOrder = xlDescending Then
arrList.Reverse
End If
argDict.RemoveAll
For Each vValue In arrList
Set coll = dictTmp(vValue)
For Each vItem In coll
argDict.Add vItem, vValue
Next vItem
Next vValue
SUB_DONE:
dictTmp.RemoveAll
Set dictTmp = Nothing
Set arrList = Nothing
Exit Sub
SUB_ERROR:
If Err.Number = 450 Then
Err.Clear
arrList.Clear
Set arrList = Nothing
Set dictTmp = Nothing
Set coll = Nothing
Err.Raise Number:=vbObjectError + 100, _
Source:="Procedure: DictSortByValue", _
Description:="Cannot sort the dictionary if the value is an object"
End If
End Sub