vba 如何计算VBA中的时间差?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28475288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate time difference in VBA?
提问by xtina1231
I need to calculate the difference of two different times.
我需要计算两个不同时间的差异。
For example,
例如,
time1 = 6:45 AM
time2 = 7:30 AM
Then, i need to convert it to hours (integer)
然后,我需要将其转换为小时(整数)
So in Basic Math, this is:
所以在基础数学中,这是:
timediff = time2 - time1
timediff = 0:45
timediff(in hrs) = 0 + (45/60)
timediff(in hrs) = 0.75
I need to do this in VBA. Can someone help me? Thanks a lot!
我需要在 VBA 中做到这一点。有人能帮我吗?非常感谢!
回答by Alex K.
DateDiff()computes this (nindicates minutes):
DateDiff()计算这个(n表示分钟):
?DateDiff("n", "6:45", "7:30") / 60
0.75
回答by eirikdaude
This was the first hit I got on a google-search for VBA timediff: http://www.ozgrid.com/forum/showthread.php?t=45698&p=231656#post231656
这是我在谷歌搜索 VBA timediff 时遇到的第一次点击:http://www.ozgrid.com/forum/showthread.php?t =45698&p =231656#post231656
I believe it should do what you want with minimal modification.
我相信它应该以最少的修改做你想要的。
The UDF defined in that post is:
该帖子中定义的 UDF 是:
Function TimeDiff(StartTime As Date, StopTime As Date)
TimeDiff = abs(StopTime-StartTime) * 86400
End Function
回答by John H Funk
This worked for me. After lots of fits and starts, it seems simple. The result value dtDuration (actually a double) is also used to update an Hours (double) field in a table.
这对我有用。经过多次反复发作,这似乎很简单。结果值 dtDuration(实际上是双精度值)也用于更新表中的小时(双精度值)字段。
Dim dtDuration As Double
dtDuration = DateDiff("s", CDate(strStarTime), CDate(strCompTime))
Me.txtCalcHours.SetFocus
Me.txtCalcHours.Text = dtDuration / 3600

