可能性太多,要VBA
弄了个VBA自定义函数,测试过了,可以解决问题,费了不少脑筋。。。。
函数名tj(t1,t2,n),参数:t1-开始时间(直接引用单元格),t2-结束时间,n-1、2、3(代表峰平谷的时间段)
Function Tj(t1, t2, n As Integer)
Dim f(2) As Integer, Ti(2), arr(2, 1) As Date
n = n - 1
arr(0, 0) = TimeValue("7:00:00")
arr(0, 1) = TimeValue("4:00:00")
arr(1, 0) = TimeValue("11:00:00")
arr(1, 1) = TimeValue("8:00:00")
arr(2, 0) = TimeValue("19:00:00")
arr(2, 1) = TimeValue("12:00:00")
s = t2 - t1 '总时长
If s < 0 Then
s = TimeValue("23:59:59") + s + TimeValue("00:00:01")
End If
'------------开始时间属于哪一时间段
Select Case t1
Case arr(0, 0) To arr(1, 0) - TimeValue("00:00:01")
f(0) = 0 'f用于记录时间段顺序
f(1) = 1
f(2) = 2
t1_ = arr(0, 1) - (t1 - arr(0, 0))
Case arr(1, 0) To arr(2, 0) - TimeValue("00:00:01")
f(0) = 1
f(1) = 2
f(2) = 0
t1_ = arr(1, 1) - (t1 - arr(1, 0))
Case Else
f(0) = 2
f(1) = 0
f(2) = 1
If t1 > arr(2, 0) Then
t1_ = arr(2, 1) - (t1 - arr(2, 0))
Else
t1_ = arr(2, 0) - arr(2, 1) - t1
End If
End Select
'-------------计算各时间段实际时长
arr(f(0), 1) = t1_
i = 0
While (s > 0 And i < 3)
Ti(f(i)) = WorksheetFunction.Min(arr(f(i), 1), s)
s = s - Ti(f(i))
i = i + 1
Wend
Ti(f(0)) = Ti(f(0)) + s
Tj = Ti(n) '返回指定时间段时长
If Tj = TimeValue("00:00:00") Then
Tj = ""
End If
End Function