[英]Calculate time difference in hours between two dates and times
我创建了一个添加名为“响应时间”的新列的宏。 我想计算两列中值之间的时间差。
我给出了一个简单的公式,
D2(列名) - C2(列名) = HH:MM 格式的总时间
当日期相同时,即 24 小时内的时间范围,宏 output 是正确的。
但是,我希望宏找到日期差异并计算新添加的“响应时间”列中的总小时数。
例如
列 C (MM/DD/YYYY hh:mm) 09/02/2020 23:00
D 列 (MM/DD/YYYY hh:mm) 09/03/2020 22:00
Output 在名为(响应时间)的新添加列中应为 25:00 小时,因为差异为 1 天 1 小时,因此总共 25 小时。
在突出显示的区域中,C 和 D 列有两个不同的日期,其中时间跨度超过 24 小时,并且 F 列中的 output 不正确。
我想要一个编码公式来比较这两列的日期时间并以 HH:MM 格式给出总小时数。
在上面突出显示的区域中,总小时数应显示为大约 162 小时。
Sub response6()
'Find and Substract (_recvd - _actual)
'Full In Gate at Ocean Terminal (CY or Port)_actual
'Full In Gate at Ocean Terminal (CY or Port)_recvd
Dim lastR As Long, cl As Range, col1 As Long
With ActiveWorkbook.Worksheets("Main")
For Each cl In .Range("1:1")
If cl.Value = "Full In Gate at Ocean Terminal (CY or Port)_recvd" Then
cl.Offset(0, 1).EntireColumn.Insert shift:=xlRight
cl.Offset(0, 1) = "Response Time"
cl.Copy
cl.Offset(0, 1).PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
Exit For ' exit the loop after finding the column
End If
Next cl
With ActiveWorkbook.Worksheets("Main")
col1 = .Cells.Find(What:="Full In Gate at Ocean Terminal (CY or Port)_actual", _
After:=.Range("A1"), LookIn:=xlValues, _
lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Column
If col1 = 0 Then MsgBox "The column header could not be found...": Exit Sub
lastR = .Cells(Rows.Count, cl.Column).End(xlUp).Row 'last row
'put formula (at once):
.Range(cl.Offset(1, 1), .Cells(lastR, cl.Offset(1, 1).Column)).Formula = _
"=" & cl.Offset(1, 0).Address(0, 0) & .Cells(2, col1).Address(0, 0) & "/" & "60"
Dim d1 As DateTime = "2/13/2018 1:50:00 PM"
Dim d2 As DateTime = "2/20/2018 1:50:00 PM"
cl.Offset(, 1).EntireColumn.NumberFormat = "hh:mm"
End With
End With
End Sub
获得时间的最简单方法是:
天(D 栏 - C 栏)*24 + 小时(D 栏 - C 栏)
分钟:分钟(D 列 - C 列)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.