VBA Timer Function

Timer Description

Returns a Single value representing the number of seconds that have elapsed since midnight.

Simple Timer Examples

Here is a simple Timer example:

Sub Timer_Example()
    MsgBox Timer
End Sub

Timer Syntax

In the VBA Editor, the syntax for the Timer function.

Timer

The Timer function contains no arguments:

Examples of Excel VBA Timer Function

Using the following code example, please try to compare sec1 and sec2.

Then, we can easily know the meaning of Timer function.

Sub Timer_Example1()
    Dim sec1 As Single
    Dim sec2 As Long
    
    sec1 = Timer
    sec2 = GetSecondsFromMidnight
    
    MsgBox "sec1 = " & sec1 & vbCrLf & _
           "sec2 = " & sec2
End Sub

Function GetSecondsFromMidnight() As Long
    Dim dt As Date
    Dim h As Integer
    Dim m As Integer
    Dim s As Integer
    
    dt = Now
    h = Hour(dt)
    m = Minute(dt)
    s = Second(dt)
    
    mins = h * 60 + m
    secs = mins * 60 + s
    
    GetSecondsFromMidnight = secs
End Function

Using the Timer function, we can measure how long it would take to run a section of VBA Code.

Sub Timer_Example2()
    Dim startSec As Single
    Dim endSec As Single
    Dim i As Long
    
    startSec = Timer
    
    ' Start Of VBA Code to Test
    For i = 1 To 500000
        DoEvents
    Next i
    ' End Of VBA Code to Test
    
    endSec = Timer
    
    MsgBox "It took " & CStr(endSec - startSec) & "s."
End Sub