Return to VBA Code Examples

VBA Timer Function

Written by

Editorial Team

Reviewed by

Steve Rynearson

Last updated on July 19, 2021

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.


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
    Next i
    ' End Of VBA Code to Test
    endSec = Timer
    MsgBox "It took " & CStr(endSec - startSec) & "s."
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as

Learn More!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples