找到最新的文件,返回最后x个文件IF在一分钟之内

时间:2013-10-22 09:58:48

标签: excel vba search excel-vba dir

我所处的情况如下: 我需要在文件夹中返回最新文件的路径。我需要返回的文件数由“ 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开始按降序运行

0 个答案:

没有答案