Search code examples
vbacoreldraw

open 3 files from folder by date


I want to open 3 files from folder by date in corel draw. I found one macro and modify but open only one file

Sub openLastModified()
    Dim folderPath As String, tableName As String, latestTblName As String
    Dim modifiedDate As Date

    folderPath = "C:\test\"

    tableName = Dir(folderPath & "*.cdr")

    Do While tableName <> vbNullString
        modifiedDate = FileDateTime(folderPath & tableName)
        If latestModified < modifiedDate Then
            latestModified = modifiedDate
            latestTblName = tableName
        End If
        tableName = Dir()
    Loop

    OpenDocument folderPath & latestTblName
End Sub

Solution

  • It looks like you want to open the three most recently modified files in your C:/test/ directory.

    The cleanest way to do that would be to load the filenames and their respective modification dates into arrays, sort them by modification date, and load the three from the bottom of your array. There are other answers on Stack Overflow to help you sort the arrays efficiently.

    Unfortunately, VBA doesn't offer any easy built-in sort functions. A slightly less clean method would be to load the filenames and their respective modification dates into a worksheet and then take advantage of Excel's sorting functions, again reading off of the bottom of your sorted range.

    Now, if you're only interested in the three most recently modified and will only ever be interested in those three, here's a quick & dirty modification to your existing code:

    Sub openLastModified()
        Dim folderPath As String, tableName As String, latestTblName(2) As String
        Dim modifiedDate As Date
        Dim latestModified(2) As Date
    
        folderPath = "C:\test\"
    
        tableName = Dir(folderPath & "*.cdr")
    
        Do While tableName <> vbNullString
            Dim i As Long
    
            modifiedDate = FileDateTime(folderPath & tableName)
    
            For i = 0 To 2
                ' Check if this file's modification date is later than that of each
                ' in the latestTblName array, starting with the most recent.
                If latestModified(i) < modifiedDate Then
                    Dim j As Long
    
                    ' Move remaining values down in the array.
                    For j = 1 To i Step -1
                        latestModified(j + 1) = latestModified(j)
                        latestTblName(j + 1) = latestTblName(j)
                    Next j
    
                    ' Place the file name & modification date in the arrays.
                    latestModified(i) = modifiedDate
                    latestTblName(i) = tableName
                    Exit For
                End If
            Next i
    
            tableName = Dir()
        Loop
    
        For i = 0 To 2
            OpenDocument folderPath & latestTblName(i)
        Next i
    End Sub