DEV Community

Wild Cat
Wild Cat

Posted on • Edited on

Calculate elapsed time in milliseconds in VBA

Calculate execution time in milliseconds

Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal milliseconds As Long)

Sub CalculateElapsedTimeInMilliseconds()

    Dim startTime   As Double
    Dim endTime     As Double
    Dim elapsedTime As Double
    Dim message     As String

    startTime = Timer

    Call Sleep(1200) 'Wait 1.2 seconds

    endTime = Timer
    elapsedTime = endTime - startTime

    message = "Time " & elapsedTime & " seconds"

    Debug.Print message 'Time 1.2 seconds

End Sub
Enter fullscreen mode Exit fullscreen mode
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal milliseconds As Long)

Sub CalculateElapsedTimeInMilliseconds()

    Dim startTime   As Double
    Dim endTime     As Double
    Dim elapsedTime As Double
    Dim message     As String

    startTime = Timer

    Call Sleep(1200) 'Wait 1.2 seconds

    endTime = Timer
    elapsedTime = endTime - startTime

    message = "Time "
    message = message & Format(Int((elapsedTime) / 60 / 60), "00") & ":"            'Hour
    message = message & Format(Int((elapsedTime) / 60) Mod 60, "00") & ":"          'Minute
    message = message & Format(Int(elapsedTime) Mod 60, "00") & "."                 'Second
    message = message & Format(Int((elapsedTime - Int(elapsedTime)) * 1000), "000") 'Millisecond

    Debug.Print message 'Time 00:00:01.200

End Sub
Enter fullscreen mode Exit fullscreen mode

Calculate time difference in seconds

Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal milliseconds As Long)

Sub CalculateElapsedTimeInSeconds()

    Dim startTime   As Date
    Dim endTime     As Date
    Dim elapsedTime As Date
    Dim message     As String

    startTime = Now

    Call Sleep(3000) 'Wait 3 seconds

    endTime = Now

    elapsedTime = endTime - startTime

    message = "Time " & Format(elapsedTime, "hh:mm:ss")

    Debug.Print message 'Time 00:00:03

End Sub
Enter fullscreen mode Exit fullscreen mode

Top comments (0)