两个date之间有多less天是在一个月内?

使用Excel公式,在一个单元格中,我想计算有多less天>= startdate<= enddate是在一个特定的月份。

示例startdate: 2014-01-15

结束date: 2015-04-02

一月: january

公式结果: 17 january days in 2014 + 31 january days in 2015 = 48

这可能吗?

我的方法是:使用一个数组公式来创build从开始date到开始date+9999的date数组。为此,它将0,1,2,… 9999天添加到开始date,直到9999天被添加。 然后计算这些日子中有多less天是在需要的月份,并且低于或等于结束date。

在这里输入图像说明

E2中的公式是

 =SUMPRODUCT((MONTH(A2+ROW($A$1:$A$10000)-1)=D2)*((A2+ROW($A$1:$A$10000)-1)<=B2)) 

请注意,如果开始date和结束date之间的时间超过9999天,则不适用。

这是第一个答案的变体,使用INDIRECT在开始和结束date(F1)之间生成一个date数组:

 =SUMPRODUCT(--(MONTH(A2-1+ROW(INDIRECT("1:"&(B2-A2+1))))=D2)) 

正如Axel Richter所提到的,您也可以使用INDEX生成date数组(F2):

 =SUMPRODUCT(--(MONTH(A2-1+ROW($A$1:INDEX($A:$A,B2-A2+1)))=D2)) 

使用这些公式的好处是,开始和结束date之间的差异没有限制。

使用INDIRECT的缺点是它是不稳定的,并在文件closures时产生一个“SAVE”提示。

INDEX方法的缺点是易受行插入/删除的影响。

在这里输入图像说明

这最好通过使用自定义公式来实现。 您需要进入VBA(右键单击表名>编辑代码),插入一个模块(右键单击VBA面板中的表名>插入>模块)并粘贴以下代码:

 Function DaysInMonthBetween(startDate As Date, endDate As Date, chosenMonth As Integer) Dim startYear, startMonth, startDay As Integer Dim endYear, endMonth, endDay As Integer Dim currentDate As Date Dim sumDays, daysInMonth As Integer sumDays = 0 startYear = Year(startDate) startMonth = month(startDate) startDay = Day(startDate) endYear = Year(endDate) endMonth = month(endDate) endDay = Day(endDate) If (startMonth > chosenMonth) Then startYear = startYear + 1 If (endMonth < chosenMonth) Then endYear = endYear - 1 If (endYear >= startYear) Then For i = startYear To endYear currentDate = DateSerial(i, chosenMonth, 1) daysInMonth = Day(Application.WorksheetFunction.EoMonth(currentDate, 0)) sumDays = sumDays + daysInMonth Next If (startMonth = chosenMonth) Then sumDays = sumDays - (startDay - 1) If (endMonth = chosenMonth) Then currentDate = DateSerial(endYear, endMonth, 1) daysInMonth = Day(Application.WorksheetFunction.EoMonth(currentDate, 0)) sumDays = sumDays - (daysInMonth - endDay) End If End If DaysInMonthBetween = sumDays End Function 

你可以通过键入=DaysInMonthBetween(startDate, endDate, chosenMonth)来使用这个自定义公式,所以如果你的开始date和结束date分别在A1和A2中,你应该input=DaysInMonthBetween(A1,A2,1)得到1月的结果, =DaysInMonthBetween(A1,A2,2) 2月的=DaysInMonthBetween(A1,A2,2)等等。