【问题标题】:How to modify the VBA code that finds Oldest File date in a folder to find Newest File date in a folder?如何修改在文件夹中查找最旧文件日期的 VBA 代码以在文件夹中查找最新文件日期?
【发布时间】:2018-02-11 23:29:40
【问题描述】:

下面的代码有助于查找文件夹中最早的文件日期,但我正在寻找可以帮助我查找文件夹中最新文件日期或最近文件日期的 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

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

【问题讨论】:

标签: excel vba


【解决方案1】:

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

首先使用相当旧的日期进行初始化:

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

并改变目标条件:

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

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

【讨论】:

  • 明白了!谢谢。很有帮助
  • 快速提问,当文件夹中没有文件时,日期值显示为“1900-01-01”。但我不希望这样显示该值,因为它没有意义。相反,当文件夹中没有文件时,我希望该值是今天的日期。你知道代码中需要改变什么来完成这个任务吗?谢谢。
猜你喜欢
  • 2012-06-12
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
相关资源
最近更新 更多