如何修改在文件夹中找到最旧文件日期的VBA代码,以在文件夹中查找最新文件日期?

时间:2018-02-11 23:29:40

标签: excel excel-vba vba

以下代码有助于查找文件夹中最早的文件日期,但我正在寻找可以帮助我在文件夹中查找最新文件日期或最近文件日期的VBA代码。

    Sub oldestdate()

Range("G10").Value = GetOldestFile("C:\Users\xxx\Downloads\My files")

End Sub


Public Function GetOldestFile(ByVal FileFolder As String, _
                              Optional ByVal FileMask As String = "*.*", _
                              Optional ByVal FullName As Boolean = True) As String

   Dim FoundFile        As String
   Dim FileDT           As Date

   Dim NewestFile       As String
   Dim NewestDT         As Date

   Dim FS As Object

   '// Get rid of any terminating '\' just to get to a known state
   If Right(Trim(FileFolder), 1) = "\" Then
      FileFolder = Left(FileFolder, Len(Trim(FileFolder)) - 1)
   End If

   '// Get First file found in described folder
   FoundFile = Dir$(FileFolder & "\" & FileMask)

   '// Default return date
   NewestDT = DateValue("1900-01-01")

   Set FS = CreateObject("Scripting.FileSystemObject")

   '// Loop through the rest of the files in that folder
   Do Until FoundFile = ""

      FileDT = FS.GetFile(FileFolder & "\" & FoundFile).DateCreated

      '// Compare Current File datetime with oldest found
      If FileDT > NewestDT Then
         NewestFile = FoundFile
         NewestDT = FileDT
      End If

      '// Get next file
      FoundFile = Dir$
   Loop

   Set FS = Nothing

   GetOldestFile = Format(NewestDT, "mm/dd/yyyy")

End Function
  

请告诉我如何在文件夹中找到最新的文件日期。

1 个答案:

答案 0 :(得分:2)

您只需要还原// Compare Current File datetime with oldest found部分以寻找较新的日期而不是较旧的日期:

首次使用合理的旧日期初始化:

NewestDT = DateValue("1900-01-01")

并改变目标条件:

...
If FileDT > NewestDT Then
   NewestDT = FileDT
   ...
End if

您可能必须调整最早的日期的初始化,我没有测试它。我还建议你改变变量的命名。