英文:
Excel - count days in each month between two dates excluding weekends
问题
我正在尝试编写一个Excel公式,该公式可以在一行单元格上拖动以给出在两个指定日期之间每个月的天数。例如:
A B C D E F
1 | 开始日期 | 结束日期 | 五月 | 六月 | 七月 | 八月 |...
---------------------------------------------------------
2 | 23/06/28 | 123/07/04 | 0 | 3 | 2 | 0 |...
我到目前为止有这个公式:
=MAX(0,MIN(IF($B2="",TODAY(),$B2),EOMONTH(DATEVALUE(C$1&"-23"),0))-MAX($A2,DATEVALUE(C$1&"-23"))+1)
这个公式会产生以下输出:
有没有办法修改这个公式以排除周末?
感谢Tom Sharpe。
英文:
I am trying to write an excel formula which can be dragged across a row of cells to give the number of days in each month between two specified dates. E.g:
1 | START DATE | END DATE | May | Jun | Jul | Aug |...
---------------------------------------------------------
2 | 28/06/23 | 04/07/123 | 0 | 3 | 2 | 0 |...
I have this so far:
=MAX(0,MIN(IF($B2="",TODAY(),$B2),EOMONTH(DATEVALUE(C$1&"-23"),0))-MAX($A2,DATEVALUE(C$1&"-23"))+1)
Which gives this output:
Is there any way to alter this in order to exclude weekends?
Credits to Tom Sharpe.
答案1
得分: 1
以下是翻译好的部分:
你可以生成表示月份的日期(月初如下),并将其放在单元格 C1
中。这是一个数组公式,所以不需要向右拖动它:
=EDATE(DATE(YEAR(A2),1,1), SEQUENCE(,12,0))
现在,要计算工作日期,您可以使用 NETWORKDAYS
函数,正如 @P.b 在评论中指出的,首先检查两个日期区间重叠的条件:
=IF(AND(C1<=$B2,EOMONTH(C1,0)>=$A2),
NETWORKDAYS(MAX(C1,$A2), MIN(EOMONTH(C1,0),$B2)),0)
这是检查两个区间 A
、B
重叠的条件:
AND(startA <= endB, endA >= startB)
在 C2
中,您也可以使用数组解决方案,例如使用 MAP
函数。我们使用 LET
函数以便于阅读和组合:
=LET(SOM,C1:N1, EOM,EOMONTH(1*SOM,0), startP,A2, endP,B2,
olaps,(SOM <= endP) * (EOM >= startP),
MAP(olaps,SOM,EOM,LAMBDA(o,s,e,IF(o=0,0,
NETWORKDAYS(MAX(startP,s),MIN(endP,e))))))
因此,不需要将公式扩展到右边。EOMONTH
在使用范围时会出错,因此我们使用以下技巧 1*SOM
将其转换为数组,使其正常工作。
英文:
You can generate the dates that represent the month (start of the month as follows) and put in on cell C1
. It is an array formula, so no need to drag it to the right:
=EDATE(DATE(YEAR(A2),1,1), SEQUENCE(,12,0))
Now to calculate the working dates you can use NETWORKDAYS
function as @P.b pointed out in the comment, checking first for the condition when two date intervals overlap:
=IF(AND(C1<=$B2,EOMONTH(C1,0)>=$A2),
NETWORKDAYS(MAX(C1,$A2), MIN(EOMONTH(C1,0),$B2)),0)
Put the formula in C2
and drag the formula to the right. Here is the output:
This is the condition to check for two intervals A
,B
overlap:
AND(startA <= endB, endA >= startB)
In C2
you can use an array solution too, via MAP
function for example. We use LET
function for easy reading and composition:
=LET(SOM,C1:N1, EOM,EOMONTH(1*SOM,0), startP,A2, endP,B2,
olaps,(SOM <= endP) * (EOM >= startP),
MAP(olaps,SOM,EOM,LAMBDA(o,s,e,IF(o=0,0,
NETWORKDAYS(MAX(startP,s),MIN(endP,e))))))
so, there is no need to extend the formula to the right. EOMONTH
gives an error when using a range, so we use the following trick 1*SOM
to convert it to an array to make it works.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论