PDA

View Full Version : Solved: caclulating birthday in a userform



lbartowski
06-20-2010, 10:08 AM
I'm creating a userform with a text box for someone to enter their date of birth. How to I convert that date into something that visual basic can understand and then do the math (in code) to that an output gives the users age in either days, weeks, months, or years, depending on which option they choose?

Hopefully that made sense. Thanks for the help.

mikerickson
06-20-2010, 12:01 PM
The DateValue function will convert from a string (e.g. "Sep 23, 1948") to an Excel serial date.

lbartowski
06-20-2010, 12:59 PM
What value would it give that date?

lbartowski
06-20-2010, 02:05 PM
I think you can see what I'm trying to do

Tinbendr
06-20-2010, 07:05 PM
There are several problems.
vOutput = DateValue(6 / 20 / 2010) / DateValue(vBirthday) & " Months"
First, the Date has to be a literal. The code thinks 6 / 20 /2010 means 6 divided by 20 divided by 2010. So you have to use a literal, meaning, you need to put it in quotes.
vOutput = DateValue("6/20/2010") / DateValue(vBirthday) & " Months"
Next, you're dividing the user date against the literal date. It should be subtracting.
vOutput = DateValue("6/20/2010") - DateValue(vBirthday) & " Months" Next, you have to use a divisor for the range needed. Since the number returned from the subtraction is in days, we use 30.
vOutput = (DateValue("6/20/2010") - DateValue(vBirthday) /30 & " Months"
But better than a fixed date, just use Date, which is the current date.
vOutput = (Date - DateValue(vBirthday) / 30 & " Months"
Finally, to trim the decimal points, use Int().
vOutput = Int((Date - DateValue(vBirthday) / 30) & " Months"

Bob Phillips
06-21-2010, 02:09 AM
Private Sub cmdOk_Click()

Dim vName, vBirthday, vOutput
vName = txtName
vBirthday = txtBirthday


If optYears.Value = True Then
vOutput = DateDiff("yyyy", Date, DateValue(vBirthday)) & " Years"
ElseIf optMonths.Value = True Then
vOutput = DateDiff("m", Date, DateValue(vBirthday)) & " Months"
ElseIf optWeeks.Value = True Then
vOutput = DateDiff("ww", Date, DateValue(vBirthday)) & " Weeks"
ElseIf optDays.Value = True Then
vOutput = DateDiff("d", Date, DateValue(vBirthday)) & " Days"
End If

lblOut = "Wow, " & vName & ", you're " & vOutput & " old!"
End Sub