VBA锻炼两个时间戳之间的天数,小时数,分钟数或秒数?

时间:2016-12-18 16:08:37

标签: excel vba timestamp

我正在尝试使用vba显示两个时间戳之间的天数或小时数或分钟数或秒数。

到目前为止,我的代码为我提供了小时数或天数。

Sub Date_Dif()

    Dim d1 As Date
    d1 = Range("A8").Value

    Dim d2 As Date
    d2 = Now

    Dim hrsDiff As Long
    hrsDiff = DateDiff("h", d1, d2)

    ActiveSheet.Range("Z5").Value = IIf(hrsDiff >= 24, _
               hrsDiff \ 24 & " days " & hrsDiff Mod 24 & " hours", _
               hrsDiff & " hours")

End Sub

我怎样才能适应这一点给我几分钟或几秒钟?

提前致谢

1 个答案:

答案 0 :(得分:4)

最简单的方法是减去日期并使用HourMinuteSecond函数。由于Date变量存储为Double,整数部分表示自纪元以来的天数,因此您可以在减法后的几天内直接使用该变量:

Dim diff As Date
diff = Now - #7/7/2016 2:15:16 PM#
Debug.Print CLng(Int(diff)) & " days"
Debug.Print Hour(diff) & " hours"
Debug.Print Minute(diff) & " minutes"
Debug.Print Second(diff) & " seconds"

将其插入您的Sub即可获得以下内容:

Sub Date_Dif()

    Dim d1 As Date
    d1 = Range("A8").Value

    Dim diff As Date
    diff = Now - d1

    ActiveSheet.Range("Z5").Value = _
               CLng(Int(diff)) & " days " & _
               Hour(diff) & " hours " & _
               Minute(diff) & " minutes " & _
               Second(diff) & " seconds"
End Sub