VBA:DateDiff年假

Ric*_*ick 2 vba access-vba

我在VBA中有以下代码返回两个日期之间的年份:DateDiff("yyyy", "10/10/1930","06/07/2008 8:30:00 AM")
它返回78,但它应该是77.
这里发生了什么?

Ken*_*ory 5

VBA的DateDiff功能不是为跟踪已用时间而设计的.该声明只是评估这一年.

请参阅此msdn文章,该文章提供了计算已用年数的函数:http://msdn.microsoft.com/library/default.asp? url =/library/en-us/ddnvbadev/html/workingwithelapsedtime.asp

Function elapsed_years_function(first_date As Date, Optional second_date As Date = 0) As Integer
' This procedure is from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvbadev/html/workingwithelapsedtime.asp
Dim elapsed_years As Integer
If second_date = 0 Then
' Did the caller pass in a date? If not, use
' the current date.
second_date = Date
End If
elapsed_years = DateDiff("yyyy", first_date, second_date)
If second_date < DateSerial(Year(second_date), Month(first_date), Day(first_date)) Then
elapsed_years = elapsed_years - 1
End If
elapsed_years_function = elapsed_years
End Function
Run Code Online (Sandbox Code Playgroud)