我有一个 Excel 电子表格,列出了工作轮班……四列对我们的目的很重要:
- 开始日期
- 开始时间
- 结束日期
- 时间结束
鉴于这些数据,我需要抽象出早上 7 点到晚上 7 点之间每个班次的小时数。
有几件事要记住...
VBA ,不考虑分钟。我不知道你是否需要分钟。
Dim i As Integer
Dim ShiftRange As Range
Dim dteStart As Date
Dim dteEnd As Date
Dim HourCount As Long
Dim MinCount As Long
Set ShiftRange = Sheet1.UsedRange
For i = 2 To ShiftRange.Rows.Count
HourCount = 0
dteStart = CDate(Cells(i, 1) + Cells(i, 2))
dteEnd = CDate(Cells(i, 3) + Cells(i, 4))
Do While dteStart <= dteEnd
If Hour(dteStart) >= 7 And Format(dteStart, "hh:mm") <= #7:00:00 PM# Then
HourCount = HourCount + 1
End If
dteStart = DateAdd("h", 1, dteStart)
Loop
MinCount = HourCount * 60
''Minutes
If CDate(Cells(i, 2)) >= #7:00:00 AM# And CDate(Cells(i, 2)) <= #7:00:00 PM# Then
MinCount = MinCount - Minute(CDate(Cells(i, 2)))
End If
If CDate(Cells(i, 4)) >= #7:00:00 AM# And CDate(Cells(i, 4)) <= #7:00:00 PM# Then
MinCount = MinCount + Minute(CDate(Cells(i, 4)))
End If
Cells(i, 6) = MinCount
Next
这假设 A、B、C 和 D 是包含日期和时间的列,并且列 F 为空。
谢谢 Remou 非常好,可行。
我进行了更改以允许部分时间
Sub DayHours()
Dim i As Integer
Dim ShiftRange As Range
Dim dteStart As Date
Dim dteEnd As Date
Dim MinCount As Double
Set ShiftRange = Sheet1.UsedRange
For i = 3 To ShiftRange.Rows.Count
MinCount = 0
dteStart = CDate(Cells(i, 3) + Cells(i, 4))
dteEnd = CDate(Cells(i, 5) + Cells(i, 6))
Do While dteStart <= dteEnd
If Format(dteStart, "hh:mm") >= #7:00:00 AM# And Format(dteStart, "hh:mm") < #7:00:00 PM# Then
MinCount = MinCount + 1
End If
dteStart = DateAdd("n", 1, dteStart)
Loop
Cells(i, 10) = MinCount / 60
Next
End Sub