Option Explicit
Sub Work_Time()
Dim etime As Date, wktime As Double, sTime As Double
Dim WE_Time, eff_date As Long
Dim a
Dim i As Long, idate As Long, sdate As Long, edate As Long, wk_day As Integer
Dim lr As Long
Const WS_time = "08:00:00"
WE_Time = Array("19:00", "17:00", "14:00")
Application.ScreenUpdating = False
Sheets("Data").Activate
a = ActiveSheet.UsedRange.Value
lr = Cells(Rows.Count, "B").End(xlUp).Row ' Last row of data
For i = 2 To lr
sdate = Int(a(i, 4)): edate = Int(a(i, 5))
wktime = 0
If sdate = edate Then ' Start & finish on the same day
wktime = a(i, 5) - a(i, 4)
Else
For idate = sdate To edate ' Loop FROM to TO dates
wk_day = Weekday(idate, vbMonday) ' Get Weekday
If wk_day < 6 Then ' Monday to Friday
etime = WE_Time(0)
Else
If wk_day = 6 Then etime = WE_Time(1) Else etime = WE_Time(2) ' Saturday or Sunday
End If
Select Case idate
Case Is = sdate ' Start Date
sTime = (a(i, 4) - Int(a(i, 4)))
wktime = wktime + (etime - sTime)
Case Is = edate ' End Date
etime = (a(i, 5) - Int(a(i, 5)))
wktime = wktime + (etime - TimeValue(WS_time))
Case Else ' "In-between" dates
wktime = wktime + (etime - sTime)
End Select
Next idate
End If
' Adjust wktime based on values in columns G and H
If a(i, 7) > 0 Then ' Check if value in column G is greater than 1
wktime = wktime - a(i, 7) ' Reduce value in column G from wktime
End If
If a(i, 8) > 0 Then ' Check if value in column H is greater than 1
wktime = wktime + a(i, 8) ' Add value in column H to wktime
End If
a(i, 6) = wktime ' Hours worked
eff_date = Application.VLookup(a(i, 2), Range("Rate_tbl"), 4, 0) ' look for Effective Date
If eff_date <> 0 And sdate >= eff_date Then ' If Sdate >= Effective date
a(i, 9) = a(i, 6) * 24 * Application.VLookup(a(i, 2), Range("Rate_tbl"), 5, 0) ' Get new Hourly rate
Else
a(i, 9) = a(i, 6) * 24 * Application.VLookup(a(i, 2), Range("Rate_tbl"), 3, 0) ' Get Hourly rate
End If
Next i
ActiveSheet.UsedRange.Value = a
With Range("J2:J" & lr)
.Formula = "=SUMIFS(I:I,B:B,B2)" ' Calculate TOTAl earnings per employee
.Value = .Value
End With
Application.ScreenUpdating = True
End Sub
changed dates in row 2
Bookmarks