我编写了一个代码来计算排除周五和周六以及非工作时间的工作时间 请注意,工作时间为 8:30 至 16:30 但如果开始日是星期四,则无法计算工作时间,如红色标记的图片所示
这是代码
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
请帮忙,谢谢
Weekday(AnyThursday,vbSunday)
返回 5。您的代码将工作日限制为 <=4, including Sundays.
将支票更改为:
If Weekday(currentDate, vbMonday) <= 5 And Not isHoliday Then