VBA Date Comparisons

Published on May 7, 2012

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
    Loop
End Sub

Tags:
Like this article? Share it!

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Privacy Policy