VBA Timer Function
In this Article
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:
1 2 3 |
Sub Timer_Example() MsgBox Timer End Sub |
Timer Syntax
In the VBA Editor, the syntax for the Timer function.
1 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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 |
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!
Learn More!