计算年龄

Access 未包括根据给定日期对人或事物的年龄进行计算的函数。 本主题包含两个自定义函数(AgeAgeMonths)的 Visual Basic for Applications (VBA) 代码,该代码将根据给定日期计算年龄。

以下函数以给定日期到当前日期的年数为单位计算年龄。

 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

以下函数计算自给定日期的上一个月以来已过去的月数。 如果给定日期为生日,则该函数返回自上一次生日以来的月数。

 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

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。