xtina1231
xtina1231

Reputation: 125

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!

Upvotes: 3

Views: 85321

Answers (3)

John H Funk
John H Funk

Reputation: 11

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

Upvotes: 0

Alex K.
Alex K.

Reputation: 175956

DateDiff() computes this (n indicates minutes):

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

Upvotes: 10

eirikdaude
eirikdaude

Reputation: 3255

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 

Upvotes: 2

Related Questions