【问题标题】:Macro to calculate the difference in hh:mm:ss计算 hh:mm:ss 差异的宏
【发布时间】:2018-04-06 11:54:15
【问题描述】:

我想计算现在和 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

【问题讨论】:

    标签: vba excel date excel-formula


    【解决方案1】:

    您是在寻找表示小时数的数字,还是在寻找文本?
    如果您想要小时数,请尝试仅减去日期并乘以 24,因此公式将为 =(NOW()-E2)*24。

    【讨论】:

    • 我希望它显示为数字,但以日期的形式显示
    【解决方案2】:

    把它放在一个模块中

        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 )
    

    作为工作表中的公式。

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

    【讨论】:

    • 很好,你可以使用diff = Abs(d2 - d1),而不是If d2 > d1 Then diff = d2 - d1 Else diff = d1 - d2
    • 我也意识到diff = diff - days 是多余的,因为后面的 Format 函数无论如何只占用时间部分。
    【解决方案3】:

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

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

    【讨论】:

    • 我确实做了那个确切的事情,但我想避免在两行中这样做以减少宏的大小......
    • 这很简洁——我不知道在 hh 周围加上括号的技巧。
    【解决方案4】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多