Search code examples
vbadatediff

If using DateDiff function, using the interval "yyyy", is the function simply subtracting the difference between the year value of date1 and date2?


Macro does not appear to be taking days into account when calculating a person's age.

Sub alcohol_test()
    Dim strBirthday As Date

    strBirthday = CDate(InputBox("Input date of birth to be verified: ", "Date of Birth"))
    If DateDiff("yyyy", strBirthday, Date) < 21 Then MsgBox ("Customer underage, sale of alcohol illegal.") _
    Else MsgBox ("Age Confirmed: Alcohol may be sold")

End Sub

Solution

  • It is even worse:
    When comparing December 31th to January 1st of the immediately succeeding year,
    DateDiff for Year ("yyyy") returns 1, even though only a single day has elapsed, says Microsoft.

    So you better compare two dates, e. g. if the birthday was before the day 21 years ago.

    Dim datBirthday as Date
    datBirthday = CDate(InputBox("Input date of birth to be verified: ", "Date of Birth"))
    If datBirthday < DateSerial(Year(Date) - 21, Month(Date), Day(Date)) Then
    

    I changed the variable name, as a beginning with "str" is a little misleading when you use date values.