本示例的功能是如何计算给定的两个日期之间的工作日,你可以选择是否将星期六或星期日也包括进去。同时本程序还允许你可入一些假期,从而在计算时将这些假期排除在外。
函数:
PublicFunctionBusinessDateDiff(ByValdDate1AsDate,ByValdDate2AsDate)AsLong
该函数的功能是计算两个日期(dDate1和dDate2)之间的工作日。下面的这些属性允许你对计算实施控制,告诉程序如何进行计算。
属性
PublicIncludeSaturdaysAsBoolean
当值为真,计算时将包括星期六,否则将星期六排除在外。
PublicIncludeSundaysAsBoolean
当值为真,计算时将包括星期日,否则将星期日排除在外。
PublicPropertyLetIncludeFirstDate(bIncAsBoolean)PublicProperty
GetIncludeFirstDate()AsBoolean
在默认情况下,BusinessDateDiff函数会将你输入的起始日包括在计算中,但不包括你输入的终止日。将该属性值设为假,计算时就不包括你输入的起始日。
PublicPropertyLetIncludeLastDate(bIncAsBoolean)
PublicPropertyGetIncludeLastDate()AsBoolean
在默认情况下,BusinessDateDiff函数不包括你输入的最后一天。将该属性值设为真,程序把你输入的最后一天包括在计算中。
方法
PublicSubHolidayAdd(dHolidayAsDate)
添加一个假期列表,以便在计算时排除这些假期。在默认情况下,没有添加任何假期。
PublicSubHolidayRemove(dHolidayAsDate)
从假期列表移除假期
PublicSubHolidayClear()
清除全部假期列表
代码清单
首先建立一个新的类模块,名为cBusinessDates,将下面的代码粘贴进去。
OptionExplicit
PublicIncludeSaturdaysAsBoolean
PublicIncludeSundaysAsBoolean
PrivatembIncludeFirstDateAsBoolean
PrivatembIncludeLastDateAsBoolean
PrivateHolidaysAsNewCollection
PublicSubHolidayAdd(dHolidayAsDate)
OnErrorResumeNext
Holidays.AdddHoliday,”D”&dHoliday
IfErrThen
Err.Clear
EndIf
EndSub
PublicSubHolidayRemove(dHolidayAsDate)
OnErrorResumeNext
Holidays.Remove”D”&dHoliday
IfErrThen
Err.Clear
EndIf
EndSub
PublicSubHolidayClear()
DimxAsLong
Forx=1ToHolidays.Count
Holidays.Remove1
Next
EndSub
PublicPropertyLetIncludeFirstDate(bIncAsBoolean)
mbIncludeFirstDate=bInc
EndProperty
PublicPropertyLetIncludeLastDate(bIncAsBoolean)
mbIncludeLastDate=bInc
EndProperty
PublicPropertyGetIncludeFirstDate()AsBoolean
IncludeFirstDate=mbIncludeFirstDate
EndProperty
PublicPropertyGetIncludeLastDate()AsBoolean
IncludeLastDate=mbIncludeLastDate
EndProperty
该函数不把dDate2包含在计算中,如果dDate2是星期日,而你又选择了计算星期日,该日期仍不计算在内。
PublicFunctionBusinessDateDiff(ByValdDate1AsDate,ByValdDate2AsDate)AsLong
DimdCurDateAsDate
DimdLastDateAsDate
DimdFirstDateAsDate
DimlDayCountAsLong
DimeDayAsVbDayOfWeek
DimdHolidayAsVariant
调整应将哪一个日期包括在计算中(第一个还是第二个)
IfIncludeFirstDateThen
dFirstDate=dDate1
Else
dFirstDate=dDate1 1
EndIf
IfIncludeLastDateThen
dLastDate=dDate2 1
Else
dLastDate=dDate2
EndIf
在所有日期中循环,并更新日期计数
dCurDate=dFirstDate
DoWhiledCurDate<>dLastDate
eDay=WeekDay(dCurDate)
IfIncludeSaturdaysAndeDay=vbSaturdayThen
lDayCount=lDayCount 1
EndIf
IfIncludeSundaysAndeDay=vbSundayThen
lDayCount=lDayCount 1
EndIf
IfeDay>=vbMondayAndeDay<=vbFridayThen
lDayCount=lDayCount 1
EndIf
dCurDate=dCurDate 1
Loop
根据假期调整日期计数
ForEachdHolidayInHolidays
如果假期在你所输入的日期范围之内
IfCDate(dHoliday)>=dFirstDateAndCDate(dHoliday)<=dLastDateThen
eDay=WeekDay(CDate(dHoliday))
IfIncludeSaturdaysAndeDay=vbSaturdayThen
lDayCount=lDayCount-1
EndIf
IfIncludeSundaysAndeDay=vbSundayThen
lDayCount=lDayCount-1
EndIf
IfeDay>=vbMondayAndeDay<=vbFridayThen
lDayCount=lDayCount-1
EndIf
EndIf
Next
BusinessDateDiff=lDayCount
EndFunction
PrivateSubClass_Initialize()
IncludeFirstDate=True
IncludeLastDate=False
IncludeSundays=False
IncludeSaturdays=False
EndSub
->