I wrote a code to calculate work hours excluding Friday and Saturday and out of work hours
note that work hours is from 8:30 to 16:30
but it fails to calculate the work hours if the start Day is thursday as it shows at the picture marked in red
this is the code
Function CountWorkHours(start_date As Date, end_date As Date, holidays As Range) As Double
Dim totalHours As Double
Dim currentDate As Date
Dim workStart As Date
Dim workEnd As Date
Dim isHoliday As Boolean
Dim holiday As Variant
Dim startHour As Date
Dim endHour As Date
' Define working hours
workStart = TimeValue("08:00:00")
workEnd = TimeValue("16:00:00")
totalHours = 0
currentDate = Int(start_date) ' Start from the date part only
' Iterate through each date from start_date to end_date
Do While currentDate <= Int(end_date)
isHoliday = False
For Each holiday In holidays
If currentDate = Int(holiday) Then
isHoliday = True
Exit For
End If
Next holiday
' Check if current date is a business day (Sunday to Thursday) and not a holiday
If Weekday(currentDate, vbSunday) <= 4 And Not isHoliday Then
' Determine the start and end times for the current day
If currentDate = Int(start_date) Then
startHour = TimeValue(start_date)
If startHour < workStart Then startHour = workStart
Else
startHour = workStart
End If
If currentDate = Int(end_date) Then
endHour = TimeValue(end_date)
If endHour > workEnd Then endHour = workEnd
Else
endHour = workEnd
End If
' Calculate the working hours for the current day
If endHour > startHour Then
totalHours = totalHours + (endHour - startHour) * 24
End If
End If
currentDate = currentDate + 1
Loop
CountWorkHours = totalHours
End Function
please help and thank you
New contributor
user26026448 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.