VBA:使用DateDiff获得与出生日期和其他日期的差的函数

问题描述 投票:0回答:1

为了得到两个日期之间的日期差,我摔了个头,但是开始时,我经常遇到问题,例如:

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

很好的例子如下:date1 =“ 02/15/2020”date2 =“ 11/16/2019”

最后我得到了月= 3天= 1为什么?因为在11末(从2019年到2020年2月)有3个月...,因此天= 1(因为16-15为1(?),并且如果日期是“ 11/14/2019”,您将获得:天= -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操作,并确定是否有条件调整结果。但是我的问题是:

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

我非常感谢和问候!

excel vba loops date datediff
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.