VBA: How to open most recent two excel files in the folder

后端 未结 2 1017
花落未央
花落未央 2021-01-16 10:58

I have trying to open the most recent two excel file in the folder so far i did open the latest file in folder but i have to open 2nd latest file in folder. refer below code

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-16 11:43

    Here's another way to tackle the problem. Create a sorted list and then process the first 2 files:

    Sub Lastest2Files()
       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
       rs.Open
    
       'build the list of files and sort
       Set fs = New FileSystemObject
       Set Folder = fs.GetFolder("C:\aatemp")
    
       For Each File In Folder.Files
          rs.AddNew
          rs("FileName") = File.Path
          rs("Modified") = File.DateLastModified
       Next
    
       rs.Sort = "Modified DESC"
    
       'process the first 2 files
       rs.MoveFirst
       Set wb2 = Workbooks.Open(rs.fields("FileName").value)
       rs.MoveNext
       Set wb2 = Workbooks.Open(rs.fields("FileName").value)
    End Sub
    

提交回复
热议问题