2017-05-31 64 views
1

我的文件都被命名爲MyFile053017.xlsmyfile052517.xls我如何獲得這個項目的名義開的日期的最後修改日期的工作簿

我試圖搶在名稱中的日期和使用,作爲最後修改日期,只是在有人打開和保存工作簿的一個實例的情況下

'Force the explicit delcaration of variables 
Option Explicit 

Sub OpenLatestFile() 

    'Declare the variables 
    Dim MyPath As String 
    Dim MyFile As String 
    Dim LatestFile As String 
    Dim LatestDate As Date 
    Dim LMD As Date 

    'Specify the path to the folder 
    MyPath = "M:\Users\Dan\Access\DiscontinueQuerry\DiscontinueQuerrySave\" 

    'Make sure that the path ends in a backslash 
    If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\" 

    'Get the first Excel file from the folder 
    MyFile = Dir(MyPath & "*.xls", vbNormal) 

    'If no files were found, exit the sub 
    If Len(MyFile) = 0 Then 
     MsgBox "No files were found...", vbExclamation 
     Exit Sub 
    End If 

    'Loop through each Excel file in the folder 
    Do While Len(MyFile) > 0 

     'Assign the date/time of the current file to a variable 
     LMD = FileDateTime(MyPath & MyFile) 

     'If the date/time of the current file is greater than the latest 
     'recorded date, assign its filename and date/time to variables 
     If LMD > LatestDate Then 
      LatestFile = MyFile 
      LatestDate = LMD 
     End If 

     'Get the next Excel file from the folder 
     MyFile = Dir 
    Loop 

    'Open the latest file 
    Workbooks.Open MyPath & LatestFile 
End Sub 
+0

你有什麼立即窗口獲得當你添加'debug.print MyFile的& 「 - 」 &LMD''LMD = FileDateTime(mypath中&MyFile的)'後? – Jeeped

+0

只是爲了確保...你是說任何名爲'MyFile053017.xls'的文件必須總是比另一個名爲'myfile052517.xls'的文件更新嗎?另外,如果實際的「最後修改日期」匹配這些名稱,那麼第一個是「最新」。 –

+0

仍然給了我最古老的文件 –

回答

1

如果你想只查看文件名以確定「最新」文件,然後不要在完整路徑上調用FileDateTime,而只需在文件名中調用下面的函數。

您需要對文件名進行一些調整,這與您的問題不完全相同。

'MyFile053017.xls >> 5/30/2017 
Function NewFileDateTime(sFile As String) 
    NewFileDateTime = DateSerial(2000 + Mid(sFile, 11, 2), _ 
             Mid(sFile, 7, 2), _ 
             Mid(sFile, 9, 2)) 
End Function 
相關問題