计算年龄-麥田
Access软件网QQ交流学习群(群号码198465573),欢迎您的加入!
首页 >技术文章> Access数据库-模块/函数/VBA


计算年龄

发表时间:2007/11/15 9:44:13 评论(0) 浏览(15776)  评论 | 加入收藏 | 复制
   
摘 要:有一个人员花名册,有"出生年月"字段(格式yyyy-mm),如何计算出每个人的年龄,和全部人员的平均年龄.
正 文:
(Q) How do I calculate the age of a person given his/her birthdate?

(A) There are several methods to do this. I'll list two methods that have been posted to the newsgroups in the recent past:

Assuming that the birthdate field is called [BDate] and is of type date, you can use the following calculation

    Age=DateDiff("yyyy", [Bdate], Now())+ _
            Int( Format(now(), "mmdd") < Format( [Bdate], "mmdd") )

Alternate: You can use this function to calculate Age.

Function Age(Bdate, DateToday) As Integer
' Returns the Age in years between 2 dates
' Doesn't handle negative date ranges i.e. Bdate > DateToday

    If Month(DateToday) < Month(Bdate) Or (Month(DateToday) = _
                Month(Bdate) And Day(DateToday) < Day(Bdate)) Then
            Age = Year(DateToday) - Year(Bdate) - 1
    Else
            Age = Year(DateToday) - Year(Bdate)
    End If
End Function

    Here's another detailed Age Checker.

'--- CODE START ---
Public Sub CalcAge(vDate1 As Date, vdate2 As Date, ByRef vYears As Integer,
ByRef vMonths As Integer, ByRef vDays As Integer)
    ' Comments  : calculates the age in Years, Months and Days
    ' Parameters:
    '    vDate1 - D.O.B.
    '    vDate2 - Date to calculate age based on
    '    vYears - will hold the Years difference
    '    vMonths - will hold the Months difference
    '    vDays - will hold the Days difference
    vMonths = DateDiff("m", vDate1, vdate2)
    vDays = DateDiff("d", DateAdd("m", vMonths, vDate1), vdate2)
    If vDays < 0 Then
        ' wierd way that DateDiff works, fix it here
        vMonths = vMonths - 1
        vDays = DateDiff("d", DateAdd("m", vMonths, vDate1), vdate2)
    End If
    vYears = vMonths \ 12 ' integer division
    vMonths = vMonths Mod 12 ' only want leftover less than one year
End Sub
'--- CODE END ---

Access软件网交流QQ群(群号:198465573)
 
 相关文章
[Access计算年龄示例]用Access根据出生年月计算年龄大小  【褚玉春  2008/6/22】
[access查询]年龄(周岁): access年龄的计算公式,a...  【蒋元根  2010/5/17】
根据出生日期计算年龄(周岁)  【lyxiong  2011/11/23】
常见问答
技术分类
相关资源
文章搜索
关于作者

麥田

文章分类

文章存档

友情链接