I would like to calculate age by getting the difference between the contents of two text boxes using VBA.
I have tried a lot of code that didn't work, and in the end I used the below module. The user form will show the result from the Excel sheet.
I want to know how to calculate the age using the user form text box only.
Module:
Function Age(Date1 As Date, Date2 As Date) As String
Dim d As Long, m As Long, y As Long
If Date2 < Date1 Then
Age = "-error-"
Exit Function
End If
m = DateDiff("m", Date1, Date2)
d = DateDiff("d", DateAdd("m", m, Date1), Date2)
If d < 0 Then
m = m - 1
d = DateDiff("d", DateAdd("m", m, Date1), Date2)
End If
y = m \ 12
m = m Mod 12
If y > 0 Then
Age = y & " Year"
If y > 1 Then
Age = Age & "s"
End If
End If
If Age <> "" And m > 0 Then
Age = Age & ", "
End If
If m > 0 Then
Age = Age & m & " Month"
If m > 1 Then
Age = Age & "s"
End If
End If
If Age <> "" And d > 0 Then
Age = Age & ", "
End If
VBA used in the user form is:
Private Sub txtDoB_AfterUpdate()
row_number = 0
Do
DoEvents
row_number = row_number + 1
item_in_review = Sheets("Data").Range("A" & row_number)
If item_in_review = txtSN.Text Then
Sheets("Data").Range("B" & row_number) = txtDoB.Text
txtAge.Value = Sheets("Data").Range("D" & row_number)
End If
Loop Until item_in_review = ""
End Sub