您的工作表日期输入和日期输出的性质可以跨越多天,因此这会使您的 CountIf 公式相当复杂。由于您必须将 A 和 B 以及 C 和 D 结合起来,才能完全了解它所指的日期。
您应该只创建一个自定义 VBA 函数,否则使用 excel 的本机函数会变得非常复杂。
第 1 步)将第 1 行的 G 列更改为上午 7:00:00,然后将其扩展到 AD 列(一直到上午 6:00:00。
步骤 2) 按 Alt + F11 并在左侧插入一个新模块。复制并粘贴此代码:
Public Function CountTimeSlots(ByVal DateIn As Range, ByVal TimeIn As Range, _
ByVal DateOut As Range, ByVal TimeOut As Range, _
ByVal DateMatch As Range, ByVal TimeMatch As Range) As Integer
Dim start As Date
Dim finish As Date
Dim match As Date
Dim i As Integer
'Initialize to 0
CountTimeSlots = 0
For i = 1 To DateIn.Rows.Count
'Combine Column A and B into a singular date
start = CDate(DateIn.Cells(i, 1).Value) + CDate(TimeIn.Cells(i, 1).Value)
'Combine Column C and D into a singular date
finish = CDate(DateOut.Cells(i, 1).Value) + CDate(TimeOut.Cells(i, 1).Value)
'Combine Column E and the vertical time stamp; Note these Match values are hardcoded to one cell
match = CDate(DateMatch.Cells(1, 1).Value) + CDate(TimeMatch.Cells(1, 1).Value)
'If the match value falls between the In and Out time, increment by 1
If (match >= start And match <= finish) Then
CountTimeSlots = CountTimeSlots + 1
End If
Next i
End Function
步骤 3) 使用单元格 G2 中的公式。然后将其向右和向下(或向下然后向右)扩展。
=CountTimeSlots($A$2:$A$7,$B$2:$B$7,$C$2:$C$7,$D$2:$D$7,$E2,G$1)
第 4 步)我建议您交换 E 列和 F 列,或者删除 F 列。乍一看,E 列中的日期与 A-D 列是分开的,这不是很直观。