How to get a DateDiff-Value in milliseconds in VBA (Excel)?

Florian picture Florian · Jun 2, 2009 · Viewed 68.8k times · Source

I need to calculate the difference between two timestamps in milliseconds. Unfortunately, the DateDiff-function of VBA does not offer this precision. Are there any workarounds?

Answer

Adam Ralph picture Adam Ralph · Jun 2, 2009

You could use the method described here as follows:-

Create a new class module called StopWatch Put the following code in the StopWatch class module:

Private mlngStart As Long
Private Declare Function GetTickCount Lib "kernel32" () As Long

Public Sub StartTimer()
    mlngStart = GetTickCount
End Sub

Public Function EndTimer() As Long
    EndTimer = (GetTickCount - mlngStart)
End Function

You use the code as follows:

Dim sw as StopWatch
Set sw = New StopWatch
sw.StartTimer

' Do whatever you want to time here

Debug.Print "That took: " & sw.EndTimer & "milliseconds"

Other methods describe use of the VBA Timer function but this is only accurate to one hundredth of a second (centisecond).