首页 > 解决方案 > VBA:使用DateDiff获取出生日期和其他日期差异的函数

问题描述

我想知道两个日期之间的日期差异,但一开始我遇到了不断的问题,例如:

如果要比较的两个值的月份相同,则结果为负数。或者在某些情况下,应该是 2 个月零 30 天的差异,它设法得到了 3 个月零 1 天的结果,如何?

一个例子如下: date1 = "02/15/2020" date2 = "11/16/2019"

我到底在哪里得到月 = 3 天 = 1 为什么?因为在 2019 年 11 月末到 2020 年 2 月 2 日有 3 个月......而天 = 1 因为 16 - 15 是 1(?),如果日期是“2019 年 11 月 14 日”,你会得到一个: 天 = -1

最后,我设法使用以下代码解决了所有问题:

Public Function GetDiffDate(birthdate As Date, otherDate As Date) As Variant
Dim CurrentDate, Years, ThisYear, Months, ThisMonth, Days

CurrentDate = CDate(birthdate )
Years = DateDiff("yyyy", CurrentDate, otherDate ) - 1
ThisYear = DateAdd("yyyy", Years, otherDate )
Months = DateDiff("m", ThisYear, otherDate )
ThisMonth = DateAdd("m", Months, ThisYear)
Days = DateDiff("d", ThisMonth, otherDate )

Do While (Days < 0) Or (Days > 0 And Months = 12) Or (Months < 0) Or (Months = 12) Or (Years < 0)

'> Here I can deduce if the days are negative, if so, then reduce the
'> account by one month and re-draw the days of difference

If Days < 0 Then 
                If Months > 0 Then Months = Months - 1
                ThisMonth = DateAdd("m", Months, ThisYear)
                Days = DateDiff("d", ThisMonth, otherDate ) * -1
            End If
            If Months < 0 Then
                ThisYear = DateAdd("yyyy", Years, CurrentDate)
                Months = DateDiff("m", ThisYear, otherDate )
                ThisMonth = DateAdd("m", Months, ThisYear)
                Days = DateDiff("d", ThisMonth, otherDate )
            End If

            If Days > 0 And Months = 12 Then
                If Years >= 0 Then Years = Years + 1
                Months = 0
            ThisMonth = DateAdd("m", Months, ThisYear)
            End If

            If Months = 12 And Days = 0 Then
                    Years = Years + 1
                    Months = 0
            End If
        Loop
    End Function

示例
我遇到的错误是这样的:birthDate = "02/15/2019" otherDate = "02/16/2020"

使用此代码,我得到:

Years = DateDiff ("yyyy", CurrentDate, otherDate)
     ThisYear = DateAdd ("yyyy", Years, otherDate)
     Months = DateDiff ("m", ThisYear, otherDate)
     ThisMonth = DateAdd ("m", Months, ThisYear)
     Days = DateDiff ("d", ThisMonth, otherDate)

结果:

年 = 1 个月 = 3 天 = -1

但真正的价值应该是

年 = 0,月 = 2,日 = 30

为此,我实施了我的 while do 和 if 条件来调整结果。但我的问题是:

如果有另一种方法可以使它更优雅?

我很感激和问候!

标签: excelvbaloopsdatedatediff

解决方案


啊,好的,明白了。您可以为此使用公式。假设单元格 A1 包含 2/15/2020,单元格 B1 包含 11/16/2019

To get the day only difference: =DATEDIF(B1,A1,"md")

To get the month only difference: =DATEDIF(B1,A1,"ym")

To get the year only difference: =DATEDIF(B1,A1,"y")

所以如果你想让它显示在一个单元格中,你可以像下面这样组合它们:

=DATEDIF(B1,A1,"md") & " day(s), "&DATEDIF(B1,A1,"ym")&" month(s), "&DATEDIF(B1,A1,"y")&" year(s)" 

This will output 30 day(s), 2 month(s), 0 year(s)

推荐阅读