How to calculate elapsed time in seconds in VBA?

phan picture phan · Feb 21, 2012 · Viewed 40.7k times · Source

I have 2 strings, strStartTime and strEndTime.

strStartTime = "12:32:54" strEndTime = "12:33:05"

I want to find out how many seconds elapsed between strStartTime and strEndTime so I did this:

Dim dtDuration as date
dtDuration = DateDiff("s", CDate(strStartTime), CDate(strEndTime))  

The result I get is dtDuration = "#1/10/1900#" in the Locals watch window.

Why does this happen? How do I get dtDuration to equal 11 for the 11 seconds that elapsed between the start and end times?

Answer

Radek picture Radek · Feb 21, 2012

Just change variable type to Long:

Dim dtDuration as Long

VBA converts numerical results of DateDiff functions into variable with date type.