I have a spreadsheet that is being used to calculate coverage for my department.

One sheet (Sheet1) has the breaks and lunch data with a key for the shifts:

sheet1

On Sheet2 I have a row of times, and a column with the shift.

I would like to make a UDF or just use a formula if possible to automatically add a 1 or .5 under some conditions. Here is how my row of times is laid out:

sheet2

I would like to create either a formula or most likely a UDF that will automaticly look up if the current time meets the criteria and put either a 1 or .5 or nothing if the criteria isn't met.

Here is the criteria for a 1:
The time (00:00) has to be in the shift, if the shift ends at (00:30) then (00:30) would have a 0;
If there is a break then the half hour of time should have a .5;
all lunches are 30 min so if there is a lunch that is on a time (04:30) then (04:30) should be 0 or blank;

有帮助吗?

解决方案

I think taht while it would be possible to do with a formula, the formula would be large and unwieldy. A UDF would be easier to create and maintain.

Try this

Function WorkTime(Breaks As Range, Shift As Variant, CurTime As Date) As Variant
    Dim Lunch As Date
    Dim Break1 As Date
    Dim Break2 As Date
    Dim v As Variant
    Dim BreakTime As Long

    With Application
        v = .Match(Shift, Breaks.Columns(1), 0)
        Lunch = .Index(Breaks.Columns(3), v)
        Break1 = .Index(Breaks.Columns(2), v)
        Break2 = .Index(Breaks.Columns(4), v)
    End With

    v = DateDiff("n", CurTime, Lunch)
    Select Case v
        Case -30 To 0
            BreakTime = 30 + v
        Case 0 To 30
            BreakTime = 30 - v
    End Select

    v = DateDiff("n", CurTime, Break1)
    Select Case v
        Case -15 To 0
            BreakTime = BreakTime + 15 + v
        Case 0 To 15
            BreakTime = BreakTime + v
        Case 15 To 30
            BreakTime = BreakTime + 30 - v
    End Select

    v = DateDiff("n", CurTime, Break2)
    Select Case v
        Case -15 To 0
            BreakTime = BreakTime + 15 + v
        Case 0 To 15
            BreakTime = BreakTime + v
        Case 15 To 30
            BreakTime = BreakTime + 30 - v
    End Select

    WorkTime = 1# - BreakTime / 30#
End Function

其他提示

Thanks everyone for the responses. This has really helped me save HOURS of work. :)

chris neilsen - Thats exactly what I was looking for. Here is the code I added to check in case the person was off shift. :)

Dim WholeShift() As String

WholeShift = Split(Shift, "-")

For i = LBound(WholeShift) To UBound(WholeShift)
    WholeShift(i) = Trim(WholeShift(i))
    If Len(WholeShift(i)) = 3 Then
        WholeShift(i) = 0 & WholeShift(i)
    End If
Next

If DateDiff("n", CDate(Left(WholeShift(0), 2) & ":" & Right(WholeShift(0), 2)), CurTime) > 0 Or DateDiff("n", CDate(Left(WholeShift(1), 2) & ":" & Right(WholeShift(1), 2)), CurTime) <= 0 Then
    CalcShiftCoverage = 0
    Exit Function
End If
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top