简体   繁体   English

查找一个月中的工作日excel VBA

[英]Finding week days in a month excel VBA

I have a sheet with Starting and Ending dates.我有一张带有开始日期和结束日期的工作表。 i want to find How many Mondays, Tue, Wed, Thu, Fri, Sat and Sundays fallen between two dates.我想找出两个日期之间有多少个星期一、星期二、星期三、星期四、星期五、星期六和星期日。 So i wrote the following function.所以我写了以下函数。 it works fine but 1st day of month is skipping.它工作正常,但每月的第一天正在跳过。

=ABS(INT((N($B$5)-L10)/7)-INT((N($B$4)-L10)/7))      'B4- Starting date and B5- Ending date

for example : 1/10/2021 and 31/10/201 starting and ending dates.例如:1/10/2021 和 31/10/201 开始和结束日期。

as per above function Total Mondays-4, Tue-4, Wed-4, Thu-4, Fri-4, Sat-5 and Sun-5按照上述功能 总计周一-4、周二-4、周三-4、周四-4、周五-4、周六-5 和周日-5

but originally Mon-4, Tue-4, Wed-4.但最初是周一 4、周二 4、周三 4。 Thu-4, Fri-5, Sat-5, Sun-5.周四 4 点、周五 5 点、周六 5 点、周日 5 点。

What happened here is 1st October, 2021 is a FRIDAY.it skips first day of a month.这里发生的事情是 2021 年 10 月 1 日是星期五。它跳过了一个月的第一天。

any help... tqs in advance...任何帮助......提前tqs......

You could use what I call a "brute force" method, where you create an array of all the relevant days, and check the matches:您可以使用我所说的“蛮力”方法,在其中创建所有相关日期的数组,并检查匹配项:

=SUMPRODUCT(N(WEEKDAY(ROW(INDEX($A:$A,$B$4):INDEX($A:$A,$B$5)))=L10))

Since you asked for a VBA solution, here's one way:由于您要求提供 VBA 解决方案,因此有一种方法:

Mnth can be any date in a month Mnth可以是一个月中的任何日期
DOW is the day of the week where 1=Sunday DOW是一周中的某一天,其中1=Sunday
The function uses the same algorithm -- testing each date in the range to see if it matches the desired day of week.该函数使用相同的算法——测试范围内的每个日期以查看它是否与所需的星期几相匹配。

Option Explicit
Function weekdaysInMonth(Mnth As Date, Optional DOW As Long = vbSunday) As Long
    Dim I As Long
    Dim dStart As Date, dEnd As Date
    Dim Cnt As Long
    
dStart = DateSerial(Year(Mnth), Month(Mnth), 1)
dEnd = DateSerial(Year(Mnth), Month(Mnth) + 1, 0)

For I = dStart To dEnd
    If Weekday(I) = DOW Then Cnt = Cnt + 1
Next I
weekdaysInMonth = Cnt

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM