首页officeexcel正文

excel用自定义函数获取某月中指定日期的数量

强国说学习2023-04-2056函数星期自定义输入Excel函数

如果我们要获取某月中指定日期的数量,例如,2009年1月中有几个星期一?用Excel内置的日期时间函数无法解决这个问题。我们可以用自定义函数的方法来解决。按Alt+F11打开VBA编辑器,单击菜单“插入→模块”,在右侧的代码窗口中输入自定义函数:

Function WeekDaysInMonth(iYear As Integer, iMonth As Integer, iDay As Integer)
Dim i, iDaysInMonth As Integer
Dim LastDateInMonth As Date
If iMonth < 1 Or iMonth > 12 Or iDay < 1 Or iDay > 7 Then
WeekDaysInMonth = "错误"
Exit Function
End If
iDaysInMonth = day(DateAdd("d", -1, DateSerial(iYear, iMonth + 1, 1)))
LastDateInMonth = DateSerial(iYear, iMonth, iDaysInMonth)
For i = iDaysInMonth – 1 To 0 Step -1
If Weekday(LastDateInMonth – i, vbMonday) = iDay Then
WeekDaysInMonth = WeekDaysInMonth + 1
End If
Next i
End Function

这个自定义函数有3个整数参数,即年、月和代表星期的数值。最后一个参数用1-7的数值表示星期一至星期日。

使用方法是在单元格中输入

=weekdaysinmonth(年,月,星期数值)

强国说学习www.qiangguoshuo.com

例如要获取2009年12月中星期日的数量,在单元格中输入公式:

=weekdaysinmonth(2009,12,7)

公式结果返回4,表示2009年12月中有4个星期日。另外,输入的参数如果超出范围,如输入“=weekdaysinmonth(2009,12,10)”,最后一个参数超出范围,公式返回“错误”。

如想转载该文章请注明出处:强国说学习-qiangguoshuo.com
强国说学习

转载声明:本站发布文章及版权归原作者所有,转载本站文章请注明文章来源!

本文链接:https://www.qiangguoshuo.com/excel/42358.html