February 14, 2019

How to Open Most Recent File from Specific Folder

How to open the most recent file from a specific folder automatically with VBA. Using this macro you can also specify which types of files you would like to open. You may like to view the most recent Excel files or PDF files or files with specific extensions. Watch the training video below and then refer to the VBA code:

Here’s the complete VBA macro code to display all recent Excel files from the invoices folder on the local disk.

Sub recentFilesSpecificFolder()
Dim myFile As String
Dim myRecentFile As String
Dim myMostRecentFile As String
Dim recentDate As Date
Dim myDirectory As String
myDirectory = “C:\invoices\”
Dim fileExtension As String
fileExtension = “*.xls”

If Right(myDirectory, 1) <> "\" Then myDirectory = myDirectory & "\"

'myFile = Dir(myDirectory & fileExtension, 0)
myFile = Dir(myDirectory & fileExtension)
'MsgBox myFile
If myFile <> "" Then
    myRecentFile = myFile
    recentDate = FileDateTime(myDirectory & myFile)
    Do While myFile <> ""
        If FileDateTime(myDirectory & myFile) > recentDate Then
             myRecentFile = myFile
             recentDate = FileDateTime(myDirectory & myFile)
         End If
         myFile = Dir
    Loop
End If
myMostRecentFile = myRecentFile
Workbooks.Open Filename:=myDirectory & myMostRecentFile

End Sub

You can view this video on YouTube.

Sample for download and practice

5 thoughts on “How to Open Most Recent File from Specific Folder

  1. good evening. i am a new user of excel vba. how can save invoice as pdf and and invoice itam deduct from total stock and how new stock automatically add in stock.

  2. If you need to find two files with different name. Lets say, i need to get most recent file starting with Apple and Mango. How do i get that?

Comments are closed.