Wednesday, January 11, 2012

Caculation of Age from DoB

It's a simple code for calculation of one's age in terms of year,monh and days





Sub calculateAge()
Dim mydob As Date, tempdob As Date, sysdate As Date
Dim y As Integer, m As Integer, d As Integer
mydob = CDate(Application.InputBox("Enter your DoB", "DoB", Default:=Format(Date, "mm/dd/yyyy"), Type:=2))
sysdate = Format(Date, "mm/dd/yyyy")
tempdate = DateSerial(Year(sysdate), Month(mydob), Day(mydob))
    If (tempdate > sysdate) Then
        y = (Year(tempdate) - Year(mydob)) - 1
        If Day(mydob) > Day(sysdate) Then
             m = -Month(mydob) - 12 * (tempdate > sysdate) + Month(sysdate) - 1
             sysdate = DateSerial(Year(sysdate), Month(sysdate), 0)
             d = Day(sysdate) - Day(mydob) + Day(Date)

        ElseIf Day(mydob) < Day(sysdate) Then
            m = -Month(mydob) - 12 * (tempdate > sysdate) + Month(sysdate)
            d = Day(Date) - Day(mydob)
     

        End If
     ElseIf (tempdate < sysdate) Then
            y = (Year(tempdate) - Year(mydob))
        If Day(mydob) > Day(sysdate) Then
             m = Month(Date) - Month(mydob) - 1
             sysdate = DateSerial(Year(sysdate), Month(sysdate), 0)
             d = Day(sysdate) - Day(mydob) + Day(Date)

        ElseIf Day(mydob) < Day(sysdate) Then
            m = -Month(mydob) - 12 * (tempdate > sysdate) + Month(sysdate)
            d = Day(Date) - Day(mydob)
     

        End If
    End If
   MsgBox "Your age  is" & y & " Years " & m & " months " & d & "days"
End Sub

No comments:

Post a Comment