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

后端 未结 2 992
花落未央
花落未央 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
    
    0 讨论(0)
  • 2021-01-16 11:50

    You can do it in one pass

    Sub findingdiff()
    Dim FileSys, objFile, myFolder, c As Object
    Dim wb1 As Workbook
    Dim wb2 As Workbook
    Dim strFilename, strFilename2
      FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                    Set FileSys = CreateObject("Scripting.FileSystemObject")
                    Set myFolder = FileSys.GetFolder(FolderName)
    
            dteFile = DateSerial(1900, 1, 1)
            For Each objFile In myFolder.Files
                If InStr(1, objFile.Name, ".xls") > 0 Then
                    If objFile.DateLastModified > dteFile Then
                        dteFile = objFile.DateLastModified
                        strFilename2 = strFilename
                        strFilename = objFile.Name
                    End If
                End If
            Next objFile
    'opening of latest file in the folder
    
      Set wb1 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)              
     Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename2)
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题