Cody Vance
asked on
Calculate Working Hours
I am creating a database and what I need is code to figure out working hours between a start date and end date minus weekends & holidays. I am not familiar with how to get this to work using queries etc. I found code below but do not know how to have this run and fill a field in the table for the form named StaplesTotalTime. The fields for start and end date/time are StaplesOutStart and StaplesOutEnd. Thanks for any help.
Public Function NetWorkhours(dteStart As Date, dteEnd As Date) As Single
Dim intGrossDays As Integer
Dim intGrossHours As Single
Dim dteCurrDate As Date
Dim i As Integer
Dim WorkDayStart As Date
Dim WorkDayend As Date
Dim nonWorkDays As Integer
Dim StartDayhours As Single
Dim EndDayhours As Single
NetWorkhours = 0
nonWorkDays = 0
'Calculate work day hours on 1st and last day
WorkDayStart = DateValue(dteEnd) + TimeValue("09:00am")
WorkDayend = DateValue(dteStart) + TimeValue("05:30pm")
StartDayhours = DateDiff("h", dteStart, WorkDayend)
EndDayhours = DateDiff("h", WorkDayStart, dteEnd)
'adjust for time entries outside of business hours
If StartDayhours < 0 Then StartDayhours = 0
If EndDayhours > 8.5 Then EndDayhours = 8.5
'Calculate total hours and days between start and end times
intGrossDays = DateDiff("d", (dteStart), (dteEnd))
intGrossHours = DateDiff("h", (dteStart), (dteEnd))
'count number of weekend days and holidays (from a table called "Holidays" that lists them)
For i = 0 To intGrossDays
dteCurrDate = dteStart + i
If Weekday(dteCurrDate, vbSaturday) < 3 Then
nonWorkDays = nonWorkDays + 1
Else
If Not IsNull(DLookup("[HolDate]", "Holidays", "[HolDate] = #" & Int(dteCurrDate) & "#")) Then
nonWorkDays = nonWorkDays + 1
End If
End If
Next i
'Calculate number of work hours
Select Case intGrossDays
Case 0 'start and end time on same day
NetWorkhours = intGrossHours
Case 1 'start and end time on consecutive days
NetWorkhours = NetWorkhours + StartDayhours
NetWorkhours = NetWorkhours + EndDayhours
Case Is > 1 'start and end time on non consecutive days
NetWorkhours = NetWorkhours - (nonWorkDays * 24)
NetWorkhours = (intGrossDays - 1 - nonWorkDays) * 8.5
NetWorkhours = NetWorkhours + StartDayhours
NetWorkhours = NetWorkhours + EndDayhours
End Select
End Function
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If the code did not do exactly what you had in mind, all you would have had to do is provide some feedback--any feedback!--to that effect.
Patrick