#type 当输入留空时 VBA 函数出错

#type Error on VBA function when input left blank

我在 Access 2010 中使用以下代码。我在一个未绑定的文本框中使用它来 return 两个计划日期 (start/Finish) 之间的工作日,用于表单上的各种计划任务。输入日期时代码可以正常工作,但是在这个特定的表单上并不是每个任务都有开始/结束日期。如果输入为空,我希望代码只是 return "" 或 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

您的代码必须接受 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 值甚至阻止调用该函数。