1

我现在的情况如下:我需要返回一个文件夹中最近一个文件的路径。我需要返回的文件数由“ numberOfFiles ”指定,并且从最近的降序排列。例如,

   File1.doc - Last modified at 8:42:00 PM
   File2.doc - Last modified at 8:43:00 PM
   File3.doc - Last modified at 8:44:00 PM

numberOfFiles = 2,应该返回一个数组;

   File3.doc's path
   File2.doc's path

使用下面的代码,这很有效。

Option Explicit
Sub test()
    Dim FileName As String
    Dim FileSpec As String

    Dim MostRecentFile As String
    Dim MostRecentDate As Date
    Dim Directory As String
    Dim resultArray() As String
    Dim groupedArray() As String

    Dim fileCounter As Integer
    Dim groupedArrayCounter As Integer
    Dim resultArrayCounter As Integer
    Dim i As Integer

    Dim numberOfFiles As Integer: numberOfFiles = 2

    Directory = "C:\Test\"
    FileSpec = "File*.doc"
    If Right(Directory, 1) <> "\" Then Directory = Directory & "\"

    fileCounter = 0
    FileName = Dir(Directory & FileSpec, 0)
    If FileName <> "" Then
        MostRecentFile = FileName
        MostRecentDate = FileDateTime(Directory & FileName)
        Do While FileName <> ""
            If FileDateTime(Directory & FileName) > MostRecentDate Then
                 MostRecentFile = FileName
                 MostRecentDate = FileDateTime(Directory & FileName)
                 ReDim Preserve resultArray(fileCounter)
                 resultArray(fileCounter) = FileName
                 fileCounter = fileCounter + 1
             End If
             FileName = Dir()
        Loop
    End If

    groupedArrayCounter = 0
    resultArrayCounter = UBound(resultArray)
    ReDim groupedArray(numberOfFiles - 1)
    For i = numberOfFiles To 1 Step -1
        groupedArray(groupedArrayCounter) = resultArray(resultArrayCounter)
        groupedArrayCounter = groupedArrayCounter + 1
        resultArrayCounter = resultArrayCounter - 1
    Next i

    MsgBox "Done"
End Sub

最后一个要求是在最后一刻提出的,我不确定如何实现它。虽然我需要能够返回numberOfFiles数量的最新文件(有效),但我必须仅在文件在 60 秒或更短的时间内相互修改时才这样做(这也需要从最近的 - 在本例中为 File3)。例如;

   If file 2 is made within 60 seconds of file 3, add it to the final array
   If file 1 is made within 60 seconds of file 2, add it to the final array
   Etc until there are no more files or we have exceeded numberOfFiles

非常感谢帮助

编辑:

我知道这可以使用 DateDiff("s", var1, var2) 以某种方式完成,我只是不完全确定逻辑将如何从数组的 uBound 开始按降序工作

4

0 回答 0