Wednesday, July 3, 2013

Calculate Age Using Nested Select Case

Sub calculateAge()
Dim tempdate As Date, sysdate As Date, mydob As Date
Dim y As Integer, m As Integer, d As Integer
mydob = CDate(Application.InputBox("Select your DoB", "DoB", Default:=Format(Date, "mm/dd/yyyy"), Type:=2))
sysdate = Format(Date, "mm/dd/yyyy")
tempdate = DateSerial(Year(Date), Month(mydob), Day(mydob))

Select Case (tempdate > sysdate)

    Case True
                y = Year(sysdate) - Year(mydob) - 1
             
                Select Case Day(mydob) > Day(Date)
                    Case True
                           
                        m = -Month(mydob) - 12 * (tempdate > sysdate) + Month(Date) - 1
                        d = Day(DateSerial(Year(Date), Month(Date), 0)) - Day(mydob) + Day(Date)
                    Case False
                        m = -Month(mydob) - 12 * (tempdate > sysdate) + Month(Date)
                        d = Day(Date) - Day(mydob)
                End Select
    Case Else
                y = Year(sysdate) - Year(mydob)
                Select Case Day(mydob) > Day(Date)
                    Case True
                           
                        m = Month(Date) - Month(mydob) - 1
                        d = Day(DateSerial(Year(Date), Month(Date), 0)) - Day(mydob) + Day(Date)
                    Case False
                        m = Month(Date) - Month(mydob)
                        d = Day(Date) - Day(mydob)
                End Select
       
End Select
MsgBox "Your Age is" & y & " years " & m & "months" & d & "days"
End Sub

No comments:

Post a Comment