Calculate Age from a Date Using VBA Function
Written by kazamraza
no comments
Classified in : User Defined (Custom) Functions, Visual Basic for Application (VBA), Macros
Date of Birth 06-Jun-90
Formula =ExactAge("06/Jun/1990")
Age as on (23/Jun/2020) 30y 0m 17d
VBA Code
Public Function ExactAge(BirthDate As Variant) As String
Dim iYear As Integer
Dim iMonth As Integer
Dim d As Integer
Dim dt As Date
Dim sResult As String
If Not IsDate(BirthDate) Then Exit Function
dt = CDate(BirthDate)
If dt > Now Then Exit Function
iYear = Year(dt)
iMonth = Month(dt)
d = Day(dt)
iYear = Year(Date) - iYear
iMonth = Month(Date) - iMonth
d = Day(Date) - d
If Sgn(d) = -1 Then
d = 30 - Abs(d)
iMonth = iMonth - 1
End If
If Sgn(iMonth) = -1 Then
iMonth = 12 - Abs(iMonth)
iYear = iYear - 1
End If
sResult = iYear & "y " & iMonth & "m " & d & "d"
ExactAge = sResult
End Function
◢ | A | B | C | D | E |
---|---|---|---|---|---|
1 | Data | Formula | Age as on 23/Jun/2020 | ||
2 | 06-Jun-90 | =ExactAge(A2) | 30y 0m 17d | ||
3 | |||||
4 |