Compute age from Date of Birth while filling out form

DAZarlengo

New Member
Joined
Oct 18, 2003
Messages
11
I have a user table that has separate fields for "Date of Birth" and "Age". When filling out the customer data form, the user would like the age to be calculated automatically in real-time when the Date of Birth is entered. (Not later, such as through an update query).

How can this be done? I'm guessing that an "on focus" event in the age box could do it. That way, when the user tabs from Date of Birth into the age box, code could be executed. But what code? And how to put that age result into the age field in the customer table.

I'd appreciate any solution, and know how to use VBA code. Thanks!
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
The best way depends on what you are using the age for. If you want the age to be current when you look at the form then don't store it but calculate it on the fly. If you want to store the age so you know their age when the record was created you could still calculate it on the fly if the date that the record was created is stored.
The easiest way to store the age would be from the update event of the "Date of Birth" field as this will recalculate the age if the DOB is eddited. the code to do it would look something like :-
Code:
Private Sub Date_of_Birth_BeforeUpdate(Cancel As Integer)
If DATE >= DateSerial(Year(DATE), Month(Me![Date of Birth]), Day(Me![Date of Birth])) Then
    Me![Age] = DateDiff("yyyy", Me![Date of Birth], DATE)
Else
    Me![Age] = DateDiff("yyyy", Me![Date of Birth], DATE) - 1
End If
End Sub

HTH

Peter
 
Upvote 0

Forum statistics

Threads
1,221,575
Messages
6,160,603
Members
451,657
Latest member
Ang24

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top