Return to VBA Code Examples

VBA Timer Function

The VBA Timer functions returns the number of seconds that have elapsed since midnight of the current day (returned as a Single data type).

Using the VBA Timer Function

The following code will show you how to use the VBA Timer Function to determine how many seconds have passed, since midnight, at the time the code is being run:

The result is:

Using the VBA Timer Function

Use VBA Timer to get Actual Time

You can convert the seconds returned from the Timer function into hh:mm:ss format to see the actual time by using the following code:

The result is:

Getting the Actual Time in VBA

Time a Section of VBA Code

If you are looking to benchmark re-written code or debate “quicker” methods in VBA you can use VBA’s built-in timer. Setting a variable equal to the timer at the start of your code and subtracting this from the timer at the end will give you a good estimate of how long a piece of code takes to run.

Performance may be affected by other programs running or trying to run while you’re macro is active, among other things.

The following example was used to see how long it would take to write the word “test” to cell A1 on Sheet1 a half million times. It took 21 seconds on my machine.

If your code is running slowly, try speeding it up by disabling screen updating.   To keep the Excel screen active while the timer is running, we can insert the DoEvents method into the code.