2017-07-06 105 views
1

我試圖打開文件夾中最近的兩個excel文件,目前爲止我打開文件夾中的最新文件但我必須打開文件夾中的第二個最新文件。請參考以下代碼。請建議如何打開第二個最近的文件?VBA:如何在文件夾中打開最近的兩個excel文件

Sub findingdiff() 
Dim FileSys, objFile, myFolder, c As Object 
Dim wb1 As Workbook 
Dim wb2 As Workbook 
    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 
        strFilename = objFile.Name 
       End If 
      End If 
     Next objFile 
'opening of latest file in the folder 

       Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename) 

End Sub 
+1

一旦你已經確定你可以簡單地再次運行循環,但最新的文件(如strFileNameNewest)有一個,如果只運行行語句 strFilename = objFile.Name 如果objFile.Name不是你已經存儲爲strFileNameNewest的那個 – AndyW

回答

1

這裏是另一種方式來解決這個問題。創建一個排序列表,然後處理第2檔:

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 
1

你能做到在一個通

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

@TsionDP你能解釋一下嗎? – Ashok

+0

@Ashok在將'strFileName'更新爲當前最新的'strFileName2'之前保留之前的最新文件,最後以'strFileName2'處的第二個最新文件結束 –