I am looking for some code that would open the most recent file in a folder if the file name starts with a specified string (e.g. Testfileyyymmdd.xlsx)
I found this code that opens the most recent file, but does not take into account the filename:
Sub GetMostRecentFile()
'To use FileSystemObject goto Tools > References and check "Microsoft Scripting Runtime"
Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date
'set path for files - change for your folder
Const myDir As String = "J:\Dailies\Test MTD"
'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)
'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If objFile.DateLastModified > dteFile Then
dteFile = objFile.DateLastModified
strFilename = objFile.Name
End If
Next objFile
'Open Workbook
Workbooks.Open "J:\Dailies\Test MTD\" & strFilename
Set FileSys = Nothing
Set myFolder = Nothing
End Sub
Can anyone help?
I found this code that opens the most recent file, but does not take into account the filename:
Sub GetMostRecentFile()
'To use FileSystemObject goto Tools > References and check "Microsoft Scripting Runtime"
Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date
'set path for files - change for your folder
Const myDir As String = "J:\Dailies\Test MTD"
'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)
'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If objFile.DateLastModified > dteFile Then
dteFile = objFile.DateLastModified
strFilename = objFile.Name
End If
Next objFile
'Open Workbook
Workbooks.Open "J:\Dailies\Test MTD\" & strFilename
Set FileSys = Nothing
Set myFolder = Nothing
End Sub
Can anyone help?