计算年龄Calculate age

Access 未包括根据给定日期对人或事物的年龄进行计算的函数。Access does not include a function that will calculate the age of a person or thing based on a given date. 本主题包含两个自定义函数(AgeAgeMonths)的 Visual Basic for Applications (VBA) 代码,该代码将根据给定日期计算年龄。This topic contains Visual Basic for Applications (VBA) code for two custom functions, Age and AgeMonths, that will calculate age based on a given date.

以下函数以给定日期到当前日期的年数为单位计算年龄。The following function calculates age in years from a given date to today's date.

 Function Age (varBirthDate As Variant) As Integer 
 Dim varAge As Variant 
 
 If IsNull(varBirthdate) then Age = 0: Exit Function 
 
 varAge = DateDiff("yyyy", varBirthDate, Now) 
 If Date < DateSerial(Year(Now), Month(varBirthDate), _ 
 Day(varBirthDate)) Then 
 varAge = varAge - 1 
 End If 
 Age = CInt(varAge) 
 End Function

以下函数计算自给定日期的上一个月以来已过去的月数。The following function calculates the number of months that have transpired since the last month supplied by the given date. 如果给定日期为生日,则该函数返回自上一次生日以来的月数。If the given date is a birthday, the function returns the number of months since the last birthday.

 Function AgeMonths(ByVal StartDate As String) As Integer 
 Dim tAge As Double 
 tAge = (DateDiff("m", StartDate, Now)) 
 If (DatePart("d", StartDate) > DatePart("d", Now)) Then 
 tAge = tAge - 1 
 End If 
 
 If tAge < 0 Then 
 tAge = tAge + 1 
 End If 
 
 AgeMonths = CInt(tAge Mod 12) 
 
 End Function

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.