Excel 如何修改在文件夹中查找最早文件日期的VBA代码,以在文件夹中查找最新文件日期?
下面的代码有助于查找文件夹中最早的文件日期,但我正在寻找一个VBA代码,它可以帮助我查找文件夹中最新的文件日期或最近的文件日期Excel 如何修改在文件夹中查找最早文件日期的VBA代码,以在文件夹中查找最新文件日期?,excel,vba,Excel,Vba,下面的代码有助于查找文件夹中最早的文件日期,但我正在寻找一个VBA代码,它可以帮助我查找文件夹中最新的文件日期或最近的文件日期 Sub oldestdate() Range("G10").Value = GetOldestFile("C:\Users\xxx\Downloads\My files") End Sub Public Function GetOldestFile(ByVal FileFolder As String, _
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
请让我知道如何在文件夹中查找最新的文件日期
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
您只需还原
//将当前文件日期时间与找到的最早的部分进行比较,以查找较新的日期,而不是较旧的日期:
首次使用合理的旧日期进行初始化:
NewestDT=DateValue(“1900-01-01”)
并更改目标条件:
...
If FileDT > NewestDT Then
NewestDT = FileDT
...
End if
您可能需要调整最早日期的初始化,我没有测试它。我还建议您更改变量的命名。请检查此项,因为它似乎就是您要查找的内容,您已经找到了!谢谢非常有用的快速问题,当文件夹中没有文件时,日期值显示为“1900-01-01”。但我不希望那个值像这样显示出来,因为它没有意义。相反,当文件夹中没有文件时,我希望该值为今天的日期。您知道为了完成这项任务需要在代码中更改什么吗?谢谢