如何创建两个函数来计算 Access 中的月份和年份的年龄

高级:需要专家编码、互操作性和多用户技能。

本文适用于 Microsoft Office Access 数据库 (.accdb 和 .mdb) 以及 Microsoft Access 项目 (.apd) 。

摘要

本文介绍如何创建两个函数,可用于根据指定的日期计算个人或事物的年龄。

注意

可以在示例文件 Qrysmp00.exe 中查看本文中使用的技术演示。

更多信息

创建函数

在模块中键入或粘贴以下代码:

'==========================================================
' General Declaration
'==========================================================
Option Explicit

'*************************************************************
' FUNCTION NAME: Age()
'
' PURPOSE:
'    Calculates age in years from a specified date to today's date.
'
' INPUT PARAMETERS:
'    StartDate: The beginning date (for example, a birth date).
'
' RETURN
'    Age in years.
'
'*************************************************************
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 NAME: AgeMonths()
'
' PURPOSE:
'  Compliments the Age() function by calculating the number of months
'  that have expired since the last month supplied by the specified date.
'  If the specified date is a birthday, the function returns the number of
'    months since the last birthday.
'
' INPUT PARAMETERS:
'    StartDate: The beginning date (for example, a birthday).
'
' RETURN
'    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

测试 Age () 和 AgeMonths () Functions

若要测试 Age () 和 AgeMonths () 函数,请执行以下步骤。

重要

以下步骤要求更改计算机上的日期。 请确保完成步骤 6 以将日期重置为当前日期。

  1. 通过使用控制面板中的日期/时间工具,记下当前日期,然后将日期设置为 2001 年 6 月 3 日。

  2. 打开模块或创建新模块。

  3. 在“视图”菜单上,单击“即时窗口”。

  4. 假设你朋友的出生日期是 1967 年 11 月 15 日,今天是 2001 年 6 月 3 日。 在“即时”窗口中键入以下行,然后按 Enter:

    ?年龄 (“11/15/67”)

    请注意,Microsoft Access 的响应值为 33 (年) 。

  5. 键入以下行,然后按 Enter:

    ?AgeMonths (“11/15/67”)

    请注意,Microsoft Access 的响应值为 6,表示自此人的上一个生日以来已过了 6 个月。 你的朋友已经 33 岁 6 个月大了。

  6. 使用控制面板中的“日期/时间”工具,将日期重置为步骤 1 中记录的当前日期。

使用 Age () 和 AgeMonths () Functions

以下过程说明如何通过在新控件中放置年龄值来标记旧订单。

  1. 在示例数据库Northwind.mdb中,在新模块中键入 Age () 和 AgeMonth () 函数。

  2. 在“设计”视图中打开“订单”窗体,并添加未绑定的文本框控件。

  3. 在新文本框控件的 ControlSource 属性中键入以下行:

    =Age ([OrderDate]) & “yrs” & AgeMonths ([OrderDate]) & “mos”

  4. 在窗体视图中查看窗体。 请注意,订单的期限显示在新文本框控件中。

参考

有关日期差异的详细信息,请在 Visual Basic 编辑器中单击“帮助”菜单上的“Microsoft Visual Basic 帮助”,在“Office 助手”或“答案向导”中键入 datediff 函数,然后单击“搜索”查看文章。