简体   繁体   中英

How to calculate time difference in VBA?

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!

DateDiff() computes this ( n indicates minutes):

?DateDiff("n", "6:45", "7:30") / 60
 0.75 

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

I believe it should do what you want with minimal modification.

The UDF defined in that post is:

Function TimeDiff(StartTime As Date, StopTime As Date) 
    TimeDiff = abs(StopTime-StartTime) * 86400 
End Function 

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.

Dim dtDuration As Double
dtDuration = DateDiff("s", CDate(strStarTime), CDate(strCompTime))

Me.txtCalcHours.SetFocus
Me.txtCalcHours.Text = dtDuration / 3600

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM