VBA Excel- How to select and open the latest added file in a folder

JoharahF

New Member
Joined
Dec 19, 2023
Messages
1
Office Version
  1. 2016
Platform
  1. Windows
VBA excel-How to select and open the latest added file in a folder
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
Is the "latest added file" another Excel workbook? Or do you just want to open up the most recent file within a folder.

This code should open the file with which has most recently been added to a directory.

You will need to add a button to your worksheet and link it to this macro.

VBA Code:
Sub OpenMostRecentFile()
    Dim folderPath As String
    Dim fileName As String
    Dim fileDate As Date
    Dim mostRecentDate As Date
    Dim mostRecentFile As String
    Dim file As Object
    
    ' Set the folder path
    folderPath = "C:\test\"
    
    ' Initialize variables
    mostRecentDate = DateSerial(1900, 1, 1)
    
    ' Check each file in the folder
    fileName = Dir(folderPath & "*.*")
    Do While fileName <> ""
        Set file = CreateObject("Scripting.FileSystemObject").GetFile(folderPath & fileName)
        fileDate = file.DateCreated
        
        ' Check if the file's creation date is more recent
        If fileDate > mostRecentDate Then
            mostRecentDate = fileDate
            mostRecentFile = fileName
        End If
        
        fileName = Dir
    Loop
    
    ' Open the most recent file
    If mostRecentFile <> "" Then
        Shell "explorer.exe " & folderPath & mostRecentFile, vbNormalFocus
    Else
        MsgBox "No files found in the folder.",
 vbExclamation
    End If
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,903
Messages
6,175,284
Members
452,630
Latest member
OdubiYouth

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top