我想找到一个特定文件夹的最新文件。
Sub FindFile()
Dim MyFolder As String
Dim MyFile As String
Dim NextRow As Long
Dim MyDateTime As Date
Dim MyDate As Date
Set sh1 = Worksheets("Sheet1")
MyFolder = "C:\"
MyFile = Dir(MyFolder & "*.pdf")
NextRow = 1
Do While Len(MyFile) > 0
MyDateTime = FileDateTime(MyFolder & MyFile)
sh1.Cells(NextRow, "A").Value = MyFolder & MyFile
sh1.Cells(NextRow, "B").Value = MyDateTime
MyDate = Int(MyDateTime)
If MyDate = Date Then
sh1.Cells(NextRow, "C").Value = "Y"
End If
NextRow = NextRow + 1
MyFile = Dir
Loop
End Sub
列出电子表格中的所有文件。不使用Sort,有没有更好的方法我可以抓取最新的文件名并将其分配给变量?
*理想情况下,我想找到该文件,甚至不必列出它们。
答案 0 :(得分:2)
如果您只想要最新文件的文件名,请比较上一个日期和新日期,并将较高的日期存储到一个变量中,并将循环中当前文件的文件名存储到另一个变量中。
最终,将存储一个高于所有其他日期的日期,这将为您提供所需的文件。在代码中,可以像这样完成:
Sub FindFileMod()
Dim MyFolder As String
Dim MyFile As String
Dim NextRow As Long
Dim MyDateTime As Date
Dim MyDate As Date
Dim MaxDateTime As Date
Dim MyFileName As String
Set sh1 = Worksheets("Sheet1")
MyFolder = "C:\"
MyFile = Dir(MyFolder & "*.pdf")
MaxDateTime = 0
NextRow = 1
Do While Len(MyFile) > 0
MyDateTime = FileDateTime(MyFolder & MyFile)
If MyDateTime > MaxDateTime Then
MaxDateTime = MyDateTime
MyFileName = MyFolder & MyFile
End If
MyFile = Dir
Loop
Debug.Print MyFileName
Debug.Print MaxDateTime
End Sub
如果有帮助,请告诉我们。 :)