macros来计算hh:mm:ss的差异
我想计算现在和列E之间hh:mm:ss之间的差异。它们都以格式dd / mm / yyyy hh:mm显示。 用下面写的代码,只考虑了hh:mm而不是日子。 所以,如果他们有2天的时间差不会加上+48小时。 代码如下:
With ws1.Range("N2:N" & lastrow1) .Formula = "=TIME(HOUR(NOW()),MINUTE(NOW()),SECOND(NOW()))-TIME(HOUR(E2),MINUTE(E2),SECOND(32))" End With
只需使用=(NOW()-E2)
并应用自定义格式[hh]:mm:ss
。 hh
周围的括号会起作用。
如果您需要几个小时,请按照@Kerry Jackson的build议乘以24。
逻辑behingdate/时间值是1天= 1,所以
- 1小时= 1/24
- 1分= 1/1440'(即24 * 60)
等等…
把它放在一个模块中
Public Function DateTimeDiff(d1 As Date, d2 As Date) Dim diff As Double diff = ABS(d2 - d1) DateTimeDiff = Fix(diff) & Format(diff, " hh:mm") End Function
然后使用
=DateTimeDiff( NOW(), E2 )
作为工作表中的公式。
您可能希望在date中添加一些validation,并在它们无效时返回错误消息。
你正在寻找一个数字是几小时,还是你在寻找文字?
如果你想要的小时数,尝试减去date,并乘以24,所以公式将是=(NOW()-E2)*24
。
Public Function timeElapsed(ByVal target_cell As Range) As String Dim hours As Long, minutes As Long, days As Long If target_cell.Value = 0 Then Exit Function x = DateDiff("n", target_cell, Now()) days = Format(Application.WorksheetFunction.RoundDown(x / 1440, 0), "00") hours = Format(Application.WorksheetFunction.RoundDown((x - (days * 1440)) / 60, 0), "00") minutes = Format(Application.WorksheetFunction.RoundDown((x - ((days * 1440) + (hours * 60))), 0), "00") timeElapsed = CStr(days) & " " & "days" & " " & CStr(hours) & ":" & CStr(minutes) End Function
结果如下:
所以你的代码变成:
With ws1 .Range("N2:N" & lastrow1).FormulaR1C1 = "=timeElapsed(RC[-9])" End With