I am using the following code in Access 2010. I use it in an unbound text box to return weekdays between two schedule dates (start/Finish) on various scheduled tasks on a form. Code is working properly when dates are entered, however on this particular form not every task will have start / end dates. I would like the code to just return "" or 0 if inputs are blank.
I should note I did not write this code myself, I am very very new to VBA and found this code online and manipulated it slightly to work for my application. How can I modify this to fit my needs?
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
ByRef
toByVal
, if that does not help, also changeDate
toVariant
. It will return-1
then. – GSerg