电脑教程
位置:首页>> 电脑教程>> office教程>> excel用自定义函数获取某月中指定日期的数量

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

  发布时间:2022-05-30 15:32:29 

标签:函数,星期,自定义,输入,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(年,月,星期数值)

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

=weekdaysinmonth(2009,12,7)

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

0
投稿

猜你喜欢

手机版 电脑教程 asp之家 www.aspxhome.com