title: Finding the Difference of Two Dates from Text Boxes
body: <p>I would like to calculate age by getting the difference between the contents of two text boxes using VBA.</p>
  
  <p>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.</p>
  
  <p>I want to know how to calculate the age using the user form text box only.</p>
  
  <p>Module:</p>
  
  <pre><code> Function Age(Date1 As Date, Date2 As Date) As String
      Dim d As Long, m As Long, y As Long
      If Date2 &lt; Date1 Then
          Age = "-error-"
          Exit Function
      End If
      m = DateDiff("m", Date1, Date2)
      d = DateDiff("d", DateAdd("m", m, Date1), Date2)
      If d &lt; 0 Then
          m = m - 1
          d = DateDiff("d", DateAdd("m", m, Date1), Date2)
      End If
      y = m \ 12
      m = m Mod 12
      If y &gt; 0 Then
          Age = y &amp; " Year"
          If y &gt; 1 Then
              Age = Age &amp; "s"
          End If
      End If
      If Age &lt;&gt; "" And m &gt; 0 Then
          Age = Age &amp; ", "
      End If
      If m &gt; 0 Then
          Age = Age &amp; m &amp; " Month"
          If m &gt; 1 Then
              Age = Age &amp; "s"
          End If
      End If
      If Age &lt;&gt; "" And d &gt; 0 Then
          Age = Age &amp; ", "
      End If
  </code></pre>
  
  <p>VBA used in the user form is:</p>
  
  <pre><code>Private Sub txtDoB_AfterUpdate()
      row_number = 0
      Do
      DoEvents
  
      row_number = row_number + 1
      item_in_review = Sheets("Data").Range("A" &amp; row_number)
  
      If item_in_review = txtSN.Text Then
          Sheets("Data").Range("B" &amp; row_number) = txtDoB.Text
          txtAge.Value = Sheets("Data").Range("D" &amp; row_number)     
      End If
  
      Loop Until item_in_review = ""    
  End Sub
  </code></pre>