vba - 两个日期之间的月数

标签 vba date excel excel-formula

我正在尝试创建一个公式或 VBA 函数来计算两个日期之间的月数,根据此规则:如果开始日期是每月 15 日或之前,或者结束日期是每月 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)但这只会在 2 个日期之间的距离超过 15 天的情况下增加一个月。例如,如果开始日期是 5/14/13-8/16/13,它会说这些日期之间有 3 个月。但是,根据我上面指定的条件,这两个日期之间的实际距离应该是 4 个月。

我如何修复这个公式?

最佳答案

这也是一个vba解决方案

Function date_diff_to_months(date1 As Date, date2 As Date) As Integer


   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

关于vba - 两个日期之间的月数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23744895/

相关文章:

java - 如何将 sql 日期转换为 Joda 日期时间?

sql-server - 由于区域设置,将字符串转换为日期时间时出错

javascript - 在 JavaScript/moment 中解释(不转换!)其他时区的日期

java - 您可以中止 POI eventmodel 中的处理表吗

excel - 根据另一列的值将一列中的值乘以 100,引用表

c# - Excel中PrintArea的最大字符串长度

sql - 两列去重

vba - Excel VBA - 范围类的自动填充方法失败

sql-server - 从 MS Access 调用存储过程会导致错误 3146

Excel 在运行 VBA 宏时删除查询表连接