用宏来计算hh:mm:ss的差异

时间:2017-10-25 11:46:59

标签: excel vba excel-vba date excel-formula

我想计算hh:mm:ss在Now和E列之间的差异。它们都以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

4 个答案:

答案 0 :(得分:4)

将其放入模块

    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 )

作为工作表中的公式。

您可能希望在日期上添加一些验证,如果它们无效,则返回错误消息。

答案 1 :(得分:4)

只需使用=(NOW()-E2)并应用自定义格式[hh]:mm:ss即可。 hh周围的括号可以解决问题 如果您需要一些小时,请按@Kerry Jackson建议的那样乘以24 逻辑behing日期/时间值是1天= 1,所以

  • 1小时= 1/24
  • 1 min = 1/1440'(即24 * 60)
    等......

答案 2 :(得分:2)

您是在寻找一个小时数,还是在寻找文字? 如果您想要小时数,请尝试减去日期,然后乘以24,因此公式为=(NOW()-E2)*24

答案 3 :(得分:1)

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

并使用如下函数作为函数:

Result

所以你的代码变成了:

With ws1
    .Range("N2:N" & lastrow1).FormulaR1C1 = "=timeElapsed(RC[-9])"
End With