如何在 MS Access 中根据某人的出生日期计算其当前年龄?
我试过了=DateDiff("yyyy", [DOB], Date())
但这只能返回他们的年龄将要是日历年,所以如果他们还没有过生日,那么它就不准确。你如何根据日历日来计算他们的年龄?
答案1
您可以在代码中添加一个函数,它可为您轻松完成此操作。转到 Visual Basic,插入一个新模块,然后粘贴以下代码:
Function Age(varDOB As Variant, Optional varAsOf As Variant) As Variant
'Purpose: Return the Age in years.
'Arguments: varDOB = Date Of Birth
' varAsOf = the date to calculate the age at, or today if missing.
'Return: Whole number of years.
Dim dtDOB As Date
Dim dtAsOf As Date
Dim dtBDay As Date 'Birthday in the year of calculation.
Age = Null 'Initialize to Null
'Validate parameters
If IsDate(varDOB) Then
dtDOB = varDOB
If Not IsDate(varAsOf) Then 'Date to calculate age from.
dtAsOf = Date
Else
dtAsOf = varAsOf
End If
If dtAsOf >= dtDOB Then 'Calculate only if it's after person was born.
dtBDay = DateSerial(Year(dtAsOf), Month(dtDOB), Day(dtDOB))
Age = DateDiff("yyyy", dtDOB, dtAsOf) + (dtBDay > dtAsOf)
End If
End If
End Function
然后,您只需创建一个控件并将控制源设置为=Age([name of the filed with the birth date])
,该函数就会准确计算年龄。
代码由 Allen Browne 提供。http://allenbrowne.com/func-08.html