在Excel中,函数DateDiff也让我们像MD一样使用atribute:查找计算月份后剩余的天数,但无法在VBA 中使用
例如
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