
Excel用自定義函數獲取某月中指定日期的數量
如果我們要獲取某月中指定日期的數量,例如,2009年1月中有幾個星期一?用Excel內置的日期時間函數無法解決這個問題。我們可以用自定義函數的方法來解決。按Alt+F11打開VBA器,單擊菜單“插入→模塊”,在右側的代碼窗口中輸入自定義函數:
Function WeekDaysInMonth(iYear As Integer, iMonth As Integer, iDay As Integer)Dim i, iDaysInMonth As IntegerDim LastDateInMonth As DateIf iMonth < 1 Or iMonth > 12 Or iDay < 1 Or iDay > 7 ThenWeekDaysInMonth = "錯誤"Exit FunctionEnd IfiDaysInMonth = day(DateAdd("d", -1, DateSerial(iYear, iMonth + 1, 1)))LastDateInMonth = DateSerial(iYear, iMonth, iDaysInMonth)For i = iDaysInMonth – 1 To 0 Step -1If Weekday(LastDateInMonth – i, vbMonday) = iDay ThenWeekDaysInMonth = WeekDaysInMonth + 1End IfNext iEnd Function
這個自定義函數有3個整數參數,即年、月和代表星期的數值。最后一個參數用1-7的數值表示星期一至星期日。
使用方法是在單元格中輸入
=weekdaysinmonth(年,月,星期數值)
例如要獲取2009年12月中星期日的數量,在單元格中輸入公式:
=weekdaysinmonth(2009,12,7)
公式結果返回4,表示2009年12月中有4個星期日。另外,輸入的參數如果超出范圍,如輸入“=weekdaysinmonth(2009,12,10)”,最后一個參數超出范圍,公式返回“錯誤”。

