确切的日期差异,以月和日为准

时间:2012-06-24 13:08:51

标签: excel vba excel-vba

DateDiff计算错误:

DateDiff("m", "30/06/2011", "24/06/2012") will return 12

但我需要返回11,因为真正的差异是11个月和25天

也许任何人都有针对此问题的具体解决方案

这对我来说是理想的:11个个月和25个

2 个答案:

答案 0 :(得分:3)

这是一个比上述定制功能更清洁的解决方案。它主要使用内置的DateDiff函数,但如果它向上舍入则调整答案。 即使第一个日期晚于第二个日期,我的功能也会给你带来差异,并且可选择添加一些文字。

Function YearsMonthsDays(Date1 As Date, _
                     Date2 As Date, _
                     Optional ShowAll As Boolean = False, _
                     Optional Grammar As Boolean = True, _
                     Optional MinusText As String = "Minus " _
                     ) As String
Dim dTempDate As Date
Dim iYears As Integer
Dim iMonths As Integer
Dim iDays As Integer
Dim sYears As String
Dim sMonths As String
Dim sDays As String
Dim sGrammar(-1 To 0) As String
Dim sMinusText As String

If Grammar = True Then
    sGrammar(0) = "s"
End If


If Date1 > Date2 Then
    dTempDate = Date1
    Date1 = Date2
    Date2 = dTempDate
    sMinusText = MinusText
End If

iYears = DateDiff("yyyy", Date1, Date2)
Date1 = DateAdd("yyyy", iYears, Date1)
If Date1 > Date2 Then
    iYears = iYears - 1
    Date1 = DateAdd("yyyy", -1, Date1)
End If

iMonths = DateDiff("M", Date1, Date2)
Date1 = DateAdd("M", iMonths, Date1)
If Date1 > Date2 Then
    iMonths = iMonths - 1
    Date1 = DateAdd("m", -1, Date1)
End If

iDays = DateDiff("d", Date1, Date2)

If ShowAll Or iYears > 0 Then
    sYears = iYears & " year" & sGrammar((iYears = 1)) & ", "
End If
If ShowAll Or iYears > 0 Or iMonths > 0 Then
    sMonths = iMonths & " month" & sGrammar((iMonths = 1)) & ", "
End If
sDays = iDays & " day" & sGrammar((iDays = 1))

YearsMonthsDays = sMinusText & sYears & sMonths & sDays
End Function

答案 1 :(得分:0)

你不会用纯DateDiff得到它。如果你使用这个custom made function,你会得到你想要的结果:

0 years, 1 months, 1 days

您还可以查看DateDif函数(最后单个f)。请注意,当结束月份的天数少于起始月份时,DateDif()仍然会给出一些可能意外的结果(即负天数)。