In order to calculate negative days (EndDate is less than StartDate), a change needs to be made to my code:
Function CountWeekDays(ByVal dtStartDate As Date, ByVal dtEndDate As Date, _
Optional ByVal lFirstDayOfWeek As VbDayOfWeek = vbMonday) As Long
Dim lWeekDays As Long
Dim dtCurrentDate As Date
Dim iNeg As Integer
If dtEndDate < dtStartDate Then
iNeg = -1
dtCurrentDate = dtStartDate
dtStartDate = dtEndDate
dtEndDate = dtCurrentDate
End If
lWeekDays = (dtEndDate - dtStartDate) \ 7
dtCurrentDate = dtStartDate + (lWeekDays * 7)
lWeekDays = lWeekDays * 5
'dtCurrentDate = dtStartDate
Do Until dtCurrentDate > dtEndDate
lWeekDays = lWeekDays + Abs(Weekday(dtCurrentDate, lFirstDayOfWeek) < 6)
dtCurrentDate = dtCurrentDate + 1
Loop
CountWeekDays = lWeekDays * iNeg
End Function
CajunCenturion, did you mean something like this:
Function CountWeekDays2(ByVal dtStartDate As Date, ByVal dtEndDate As Date, _
Optional ByVal lFirstDayOfWeek As VbDayOfWeek = vbMonday) As Long
Dim lWeekDays As Long
Dim lWeekStart As Integer
Dim lWeekEnd As Integer
lWeekStart = Weekday(dtStartDate, vbMonday)
If lWeekStart > vbFriday Then lWeekStart = vbFriday
lWeekEnd = Weekday(dtEndDate, vbMonday)
If lWeekEnd > vbFriday Then lWeekEnd = vbFriday
dtStartDate = dtStartDate - lWeekStart + 1
dtEndDate = dtEndDate - lWeekEnd + 1
lWeekDays = DateDiff("w", dtStartDate, dtEndDate, vbMonday) * 5
lWeekDays = lWeekDays - lWeekStart + lWeekEnd
CountWeekDays2 = lWeekDays
End Function
Both return equal values (negative or positive).
Maybe you have the time to check the performance of the two?
In order to check holidays with these, an array of the holiday dates could be past and looped through checking if the holiday falls between the start and end dates, and if so, check if those holidays are on a weekend and keep a count of the matches - 6 additional lines of code - which I will post later. The only problem with holidays, is that the dates are different year to year and you would have to be careful not to have a date range that goes beyond the holiday dates passed, other than that, a simple array and the check in these subs will work fine.
MichaelRed's code may be easier to understand and work with though. [/b][/i][/u]*******************************************************
General remarks:
If this post contains any suggestions for the use or distribution of code, components or files of any sort, it is still your responsibility to assure that you have the proper license and distribution rights to do so!