The VBA Timer Function


The VBA Timer Function returns a Single data type, representing the number of seconds that have elapsed since midnight of the current day.

The function takes no arguments and therefore the syntax of the function is simply:


VBA Timer Function Examples

Example 1 - Single Call to the VBA Timer Function

' Return the number of seconds since midnight
Dim secs As Single
secs = Timer( )
' The variable secs is now equal to 44004.21 (current time is 12:13:24)

After running the above VBA code at 12:13:24 PM, the variable secs was equal to 44004.21.

Note that the value returned from the Timer function also includes partial seconds, which is useful if you want to accurately time sections of VBA code.

Example 2 - Use of the Timer Function to Time a Section of VBA Code

The following example shows how the Timer function can be used to time a section of VBA code.

' Time a section of VBA code using the Timer function
Dim secs1 As Single
Dim secs2 As Single
secs1 = Timer( )
' Code to be timed
' End of code to be timed
secs2 = Timer( )
' Display the time difference in a MessageBox
MsgBox( "Time taken to run code:"  &  vbNewLine  &  secs2 - secs1  &  " seconds" )

After running the above VBA code, the following message box is displayed:

Message Box Showing Result of Timer Calculation