VBA 锻炼两个时间戳之间的天数、小时数、分钟数或秒数?
Posted
技术标签:
【中文标题】VBA 锻炼两个时间戳之间的天数、小时数、分钟数或秒数?【英文标题】:VBA workout how many days, hours, minutes or seconds between two timestamps? 【发布时间】:2017-05-03 18:37:12 【问题描述】:我正在尝试使用 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】:最简单的方法是减去日期并使用Hour
、Minute
和Second
函数。由于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
【讨论】:
clng
是一个数字转换函数,它删除千位分隔符、精度 - 1 而不是 1.22 - 和货币符号。如果您只想要几分钟,minute
这里似乎是错误的,因为如果我是对的,它与小时和天有关。改为使用datediff("n","start","end")
。以上是关于VBA 锻炼两个时间戳之间的天数、小时数、分钟数或秒数?的主要内容,如果未能解决你的问题,请参考以下文章
MySql计算两日期时间之间相差的天数,秒数,分钟数,周数,小时数
使用 Pandas 的两个时间戳之间的每小时时间序列(以分钟为单位)