两个date之间的月数
我正在尝试创build一个计算两个date之间的月数的公式或VBA函数,根据以下规则:如果开始date是月份的15日或之前,或者结束date是月份的15日之后,那么那个月就很重要。
例如:
Start Date End Date Output ---------- --------- -------- 1/5/2014 2/16/2014 2 months 1/17/2014 2/16/2014 1 month 1/16/2014 2/5/2014 0 months
我已经尝试了=DATEDIF(A2, B2, "M") + IF( DATEDIF(A2, B2, "MD")>=15, 1, 0)
但是这只会增加一个月,如果两天之间的距离date超过15个。例如,如果开始date是5/14 / 13-8 / 16/13,则会说在这些date之间有3个月。 但是,根据我上面指定的条件,这两个date之间的实际距离应该是4个月。
我能修正这个公式吗?
编辑:帐户多年…
=( (YEAR(B1)*12+MONTH(B1)) - (YEAR(A1)*12+MONTH(A1)) ) + ( IF(DAY(A1)<=15,1,0)+IF(DAY(B1)>15,1,0) )
这是一个vba解决scheme
Function date_diff_to_months(date1 As Date, date2 As Date) Dim y1 As Integer Dim y2 As Integer Dim d1 As Integer Dim d2 As Integer Dim m1 As Integer Dim m2 As Integer Dim m_diff As Integer Dim y_diff As Integer Dim month_adjustment As Integer y1 = Year(date1) y2 = Year(date2) m1 = Month(date1) m2 = Month(date2) d1 = Day(date1) d2 = Day(date2) m_diff = m2 - m1 y_diff = (y2 - y1) * 12 If (m_diff > 0 Or y_diff > 0) Then If (d1 <= 15 And d2 >= 15) Then month_adjustment = 1 ElseIf (d1 >= 15 And d2 <= 15) Then month_adjustment = -1 End If End If date_diff_to_months = m_diff + y_diff + month_adjustment End Function