使用 VBA 无法获得两个日期之间的月份和剩余天数的差异

Using VBA unable to get the difference between two dates in months and remaining days

在 Excel 函数 DateDiff 中,也让我们使用像 MD 这样的属性:找到剩余天数 post 计算月份,但无法在 VBA[=13 中使用=]

例如

Start Date: 7/8/2020
End Date: 6/3/2021

答案应该是:10 个月 26 天

请告诉我使用 VBA excel

的方法
fromDate = TextBox1.Value
Dim toDate As Date
toDate = TextBox2.Value  
diff = DateDiff("m", fromDate, toDate) – To find months
totaldays = DateDiff("d", fromDate, toDate) – To find total days
projected_Date = DateAdd("m", (diff), fromDate) – Adding the month to start date
days_diff_proj = DateDiff("d", projected_Date, toDate) Finding the remaining days                  
TextBox3.Value = CStr(diff) + " Months " + CStr(days_diff_proj) + " Days "
    

我假设 toDate 总是大于 fromDate。

你第一次计算月差的尝试很好。但是,由于 VBA 进行四舍五入,您需要注意计算出的月数太大的情况 - 在这种情况下,通过将月数减一来进行计算。

Dim month_diff_proj As Long
month_diff_proj = DateDiff("m", fromDate, toDate)

Dim projected_Date As Date, days_diff_proj As Long
projected_Date = DateAdd("m", month_diff_proj, fromDate)

If projected_Date > toDate Then
    month_diff_proj = month_diff_proj - 1    ' reduce by 1 month 
    projected_Date = DateAdd("m", month_diff_proj, fromDate)
End If
days_diff_proj = DateDiff("d", projected_Date, toDate)

Debug.Print month_diff_proj, days_diff_proj