共用方式為


計算年齡

Access 不包含會根據指定日期計算人員或事物年齡的函式。 本主題包含 Visual Basic for Applications (VBA) 程式碼,這兩個自訂函式 AgeAgeMonths會根據指定的日期計算年齡。

下列函數以年為單位,計算從指定日期起到今天的年齡或年份。

 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 支援與意見反應