In this post we will see how to open the latest excel file from the folder using VBA code.
The problem can be broken into three parts i.e. first we will create a list of excel; l file in the folder and then we will sort the last modified date value for those files in the folder and ultimately we will open the latest excel file in the folder using VBA code.
Open VB editor from Develop the workbook in which we will write the code to open the most recent excel file from a folder.
Insert a module in which we will the VBA code.
Now double click the newly created module to open that and paste the below code in the module.
Dim rs As ADODB.Recordset
Dim fs As FileSystemObject
Dim Folder As Folder
Dim File As File
‘create a recordset to store file info
Set rs = New ADODB.Recordset
rs.Fields.Append “FileName”, adVarChar, 100
rs.Fields.Append “Modified”, adDate
‘build the list of files and sort
Set fs = New FileSystemObject
Set Folder = fs.GetFolder(“D:\Excel Website”)
For Each File In Folder.Files
rs(“FileName”) = File.Path
rs(“Modified”) = File.DateLastModified
rs.Sort = “Modified DESC”
‘process the first 2 files
Set wb2 = Workbooks.Open(rs.Fields(“FileName”).Value)
Make a reference to “Microsoft Scripting Runtime” and “Microsoft Activex Data Objects” library by clicking Tools->References in VB editor.
This code requires the folder location from which we want to open the most latest excel file using VBA.
Now run the code by pressing F5 or by pressing play button in the VB editor and this code will open the most recent excel file.
Hope this helped.