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

后端 未结 2 991
花落未央
花落未央 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: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
    

提交回复
热议问题