我在Access 2010中使用以下代码。我在未绑定的文本框中使用它来返回表单上各种计划任务的两个计划日期(开始/结束)之间的工作日。输入日期时代码正常工作,但在此特定表单上并非每个任务都有开始/结束日期。如果输入为空,我希望代码只返回“”或0。
我应该注意到我自己并没有写这个代码,我对VBA非常新,并且在网上找到了这个代码并稍微操作它以适用于我的应用程序。如何修改它以满足我的需求?
Public Function Weekdays( ByRef startDate As Date, _
ByRef endDate As Date _
) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.
' If your weekend days do not include Saturday and Sunday and
' do not total two per week in number, this function will
' require modification.
On Error GoTo Weekdays_Error
' The number of weekend days per week.
Const ncNumberOfWeekendDays As Integer = 2
' The number of days inclusive.
Dim varDays As Variant
' The number of weekend days.
Dim varWeekendDays As Variant
' Temporary storage for datetime.
Dim dtmX As Date
' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", _
date1:=startDate, _
date2:=endDate) + 1
' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", _
date1:=startDate, _
date2:=endDate) _
* ncNumberOfWeekendDays) _
+ IIf(DatePart(Interval:="w", _
Date:=startDate) = vbSunday, 1, 0) _
+ IIf(DatePart(Interval:="w", _
Date:=endDate) = vbSaturday, 1, 0)
' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)
Weekdays_Exit:
Exit Function
Weekdays_Error:
Weekdays = -1
Resume Weekdays_Exit
End Function
答案 0 :(得分:3)
你的代码必须接受Null值,因为Date是一个不能容忍Null的数据类型,你有两个方法,改变函数的声明。
Public Function Weekdays( ByRef startDate As Date, _
ByRef endDate As Date _
) As Integer
要,
Public Function Weekdays(startDate, endDate) As Integer
这样代码可以有Null值,因此可以添加一些,
Public Function Weekdays(startDate, endDate) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.
' If your weekend days do not include Saturday and Sunday and
' do not total two per week in number, this function will
' require modification.
On Error GoTo Weekdays_Error
If IsNull(startDate) Or IsNull(endDate) Then
Weekdays = 0
Exit Function
End If
Const ncNumberOfWeekendDays As Integer = 2
'so on....
或者另一种方法是确保使用Nz()
来传递日期,或者如果你有Null值,甚至阻止调用函数。