Code:
Public Function HCalc(DateST As Date, DateEN As Date) As Double
Const StartTime As Date = #7:00:00 AM# 'start time of work day
Const EndTime As Date = #5:00:00 PM# ' end time of work day
Dim StDate As Date
Dim StDateD As Date
Dim StDateT As Date
Dim EnDate As Date
Dim EnDateD As Date
Dim EnDateT As Date
Dim Result As Double
Dim ResultS As Double
Dim ResultE As Double
Dim MinDay As Double
Dim RegCh As Boolean
If IsNull(DateST) Or IsNull(DateEN) or Format(DateST, "Short Time") < StartTime Or Format(DateEN, "Short Time") > EndTimeThen
HCalc = 0
Else
StDate = CDate(DateST)
EnDate = CDate(DateEN)
'
' Extract the date portion of the two timestamps
'
StDateD = CDate(Format(StDate, "Short Date"))
EnDateD = CDate(Format(EnDate, "Short Date"))
'
' If start and end are the same date, the result is the difference in minutes
'
If StDateD = EnDateD Then
Result = DateDiff("n", StDate, EnDate)
Else
'
MinDay = DateDiff("n", StartTime, EndTime)
'
' Extract the time portion of the two timestamps
'
StDateT = Format(StDate, "Short Time")
EnDateT = Format(EnDate, "Short Time")
'
' Next, we calculate the minutes for the first (partial day)
ResultS = DateDiff("n", StDateT, EndTime)
Debug.Print Weekday(StDateD), StDateD, ResultS, ResultS, "Start day"
Result = ResultS '+ ResultE
' Adjust the starting date forward by 1. If the difference between the two dates
' was only 1 day, we have already calculated the contributions of the first and
' last dates, and we won't execute the following loops.
StDateD = DateAdd("d", 1, StDateD)
' EnDateD = DateAdd("d", -1, EnDateD)
' We walk through the dates in between
Do Until StDateD = EnDateD
'
' We want to skip Saturdays (7) and Sundays (1)
If (Weekday(StDateD) > 1) And (Weekday(StDateD) < 7) Then
'
' We always add the value for a day
Result = Result + MinDay
Debug.Print Weekday(StDateD), StDateD, MinDay, Result
'
Else
Debug.Print Weekday(StDateD), StDateD, 0, Result
End If
'
' Increment the date - we do this AFTER the rest of the loop because we already
' did the first increment outside the loop. Because we will fall out of the outer
' loop after the last increment, we won't add anything for the last day (which
' was already handled before the loop).
'
StDateD = DateAdd("d", 1, StDateD)
Loop
End If
'
' Convert the total minutes to hours and round to the nearest hundredth
'
' Next, we calculate the minutes for the last (partial day)
ResultE = DateDiff("n", StartTime, EnDateT)
Result = Result + ResultE
Debug.Print Weekday(EnDateD), EnDateD, ResultE, Result, "End Day"
HCalc = Round(Result / 60, 2)
End If
End Function