Det er lidt tricky på grund af de skiftende antal dage per måned og skudår. Men denne gør det rigtigt:
' Returns the difference in full months from DateOfBirth to current date,
' optionally to another date.
' Returns zero if AnotherDate is earlier than DateOfBirth.
'
' Calculates correctly for:
' leap Months
' dates of 29. February
' date/time values with embedded time values
' any date/time value of data type Date
'
' DateAdd() is, when adding a count of months to dates of 31th (29th),
' used for check for month end as it correctly returns the 30th (28th)
' when the resulting month has 30 or less days.
'
' 2015-11-24. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function AgeMonths( _
ByVal DateOfBirth As Date, _
Optional ByVal AnotherDate As Variant) _
As Long
Dim ThisDate As Date
Dim Months As Long
' If IsDateExt(AnotherDate) Then
If IsDate(AnotherDate) Then
ThisDate = CDate(AnotherDate)
Else
ThisDate = Date
End If
' Find difference in calendar Months.
Months = DateDiff("m", DateOfBirth, ThisDate)
If Months > 0 Then
' Decrease by 1 if current date is earlier than birthday of current year
' using DateDiff to ignore a time portion of DateOfBirth.
If DateDiff("d", ThisDate, DateAdd("m", Months, DateOfBirth)) > 0 Then
Months = Months - 1
End If
ElseIf Months < 0 Then
Months = 0
End If
AgeMonths = Months
End Function
År kan du så regne ud ved at dividere med 12 og runde ned. Resten vil være måneder:
TotalMåneder = AgeMonths
HeleÅr = TotalMåneder \ 12
RestMåneder = TotalMåneder Mod 12
Alle mine datofunktioner:
https://github.com/GustavBrock/VBA.Date