我有一份Excel电子表格,其中列出了作业转移......对我们来说非常重要的四列:
根据这些数据,我需要抽取每次班次在早上7点和晚上7点之间的小时数。
要记住的一些事项......
答案 0 :(得分:0)
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是包含日期和时间的列,并且colum F为空。
答案 1 :(得分:0)
谢谢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