Search code examples
excelvbauserform

Subtract 2 dates from different textbox and auto populate age in 3rd textbox


How to populate age automatically after i enter Date of birh

I want to subtract 2 dates from different textbox and auto populate age in 3rd textbox

Textbox7 has TODAY'S DATE

Textbox3 has Date of Birth

in textbox4 i want to auto populate AGE only in (years).

Your help is appreciated.

Thanks in advance!

Sherry


Solution

  • Use If/ElseIf code blocks for each of the valid entry formats and add the century as appropriate.

    Private Sub TextBox3_AfterUpdate()
    
        Dim s As String, dob As Date
        Dim age As Long, bday As Date
        
        s = TextBox3.Text 'dob
        TextBox4 = "" ' age
        If Len(s) = 0 Then
             Exit Sub
        End If
        
        If IsNumeric(s) Then
            If s Like "##" Then
                dob = DateSerial("19" & s, 1, 1)
            ElseIf TextBox3 Like "0##" Then
                dob = DateSerial("2" & s, 1, 1)
            ElseIf TextBox3 Like "####" Then
                dob = DateSerial(s, 1, 1)
            Else
                TextBox3 = ""
                Exit Sub
            End If
        ElseIf s Like "*#/*#/*##" And IsDate(s) Then
            dob = DateValue(s)
        Else
            TextBox3 = ""
            Exit Sub
        End If
        
        ' calc age if valid dob
        If IsDate(dob) Then
            If dob > Date Then
                MsgBox "Birthday in future ?"
            Else
                TextBox3 = Format(dob, "dd/mm/yyyy")
                
                '  had birthday this year ?
                bday = DateSerial(Year(Date), Month(dob), Day(dob))
                age = Year(Date) - Year(dob)
                If Date < bday Then age = age - 1
                
                TextBox4 = age
            End If
        Else
            TextBox3 = ""
        End If
        
    End Sub