[英]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.