如果我们要获取某月中指定日期的数量,例如,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的数值表示星期一至星期日。
使用方法是在单元格中输入
利用VBA禁用Excel中的F1键
如果在使用Excel过程中习惯使用F2键切换到单元格编辑状态,有时可能会不小心错按了F1键而弹出Excel帮助窗口,特别是对于键盘较小的笔记本这种情况就更容易出现。如果是Excel 2007/2010,Excel帮助窗口会覆盖工作表窗口,显得有些不便。如果要禁用F1键,可以用下面的VBA代码。 在Excel中按快捷键A
=weekdaysinmonth(年,月,星期数值)
例如要获取2009年12月中星期日的数量,在单元格中输入公式:
=weekdaysinmonth(2009,12,7)
公式结果返回4,表示2009年12月中有4个星期日。另外,输入的参数如果超出范围,如输入“=weekdaysinmonth(2009,12,10)”,最后一个参数超出范围,公式返回“错误”。
excel实现按指定的单元格颜色进行计数或求和实例教程
如果Excel工作表的某区域中包含不同的底纹颜色,我们可以用一个自定义函数对该区域按指定的单元格颜色进行计数或求和。方法是: 1.按Alt F11,打开VBA编辑器。 2.单击菜单“插入→模块”,将插入名称为“模块1”的模块,在右侧的代码窗口中输入下列代码: F