VBA Date Comparisons

VBA has native Date functions as well as a Date data type that allow for comparing and storing date information. The DateAdd function returns a future date (or previous date using a negative interval) using the specified interval. The interval can be in seconds, minutes, hours, days, months, weeks, or years. The DateDiff function will return the difference between two days in the specified interval.

The example below calculates a target date 180 days prior to the current date then finds all files in the specified folder that were last modified prior to the target date.

Sub Test()
    ArchiveFiles ActiveDesignFile.Path, 180
End Sub


Sub ArchiveFiles(strPath As String, numDays As Long)
    Dim dateTarget As Date
    Dim iDays As Long
    Dim strFile As String
    ' Target date is numDays before today
    dateTarget = DateAdd("d", numDays * -1, Date)
    ' find all files in current folder
    strFile = Dir(strPath & "\*")
    Do While Len(strFile) > 0
        ' get the number of days since the file was created or last modified
        iDays = DateDiff("d", FileDateTime(strFile), dateTarget)
        ' If older than numDays send to archive
        If iDays > numDays Then
            ' Archive file
        End If
        strFile = Dir
End Sub

Rod Wing

Rod is the Senior Systems Analyst at EnvisionCAD and has extensive experience in GIS, cartography, plotting, scanning, raster editing/manipulation, publishing, and file/data translations. He instructs MicroStation classes ranging from fundamentals to advanced.


Leave a Reply

Your email address will not be published. Required fields are marked *