The VBA Timer Function
Description
The VBA Timer returns the fractional value of a second.
- Syntax
Timer
- Return Value
The Timer function in Windows returns fractions of a second. The Macintosh has a one-second timing resolution.
Example 1 – Using the Timer Function to Calculate the Total Time
Steps:
- Press Alt + F11 to open the Microsoft Visual Basic for Applications.
- Select the Insert tab.
- Click Module.
A new module will open.
- Enter the following code into the module.
Sub Do_Until_Etample1()
Dim ss_ST As Single
ss_ST = Timer
Dim t As Long
t = 1
Do Until t = 100000
Cells(t, 1).Value = t
t = t + 1
Loop
MsgBox Timer - ss_ST
End Sub
- After running the code, you will find a message box showing the code running time:
Read More: Excel VBA to Create Timer Loop
Example 2 – Applying the VBA Timer Function to Get the Actual Time
Steps:
- Open a new module.
- Use the following code in the module.
Sub Gettingss_theActualTime()
Dim ss_secondsSince As Single
Dim ss_cTime As Double
Dim ss_theActualTime As Variant
ss_secondsSince = Timer()
ss_cTime = ss_secondsSince / (86400)
ss_theActualTime = Format(ss_cTime, "hh:mm:ss")
MsgBox "The time elapsed since midnight is (in seconds)" & " " & ss_secondsSince & vbNewLine & _
"The time in actual format:" & " " & ss_theActualTime
End Sub
- After running the code, you will get the time in seconds and in hh:mm:ss format in the message box.
Read More: How to Create a Timer with Milliseconds in Excel VBA
Example 3 – Testing the Processor Speed using the VBA Timer Function
Steps:
- Open a new Module.
- Enter the code.
Sub ss_BenchMark()
Dim ss_Count As Long
Dim ss_BenchMark As Double
ss_BenchMark = Timer
For ss_Count = 1 To 500000
Sheet1.Cells(1, 1) = "test run"
Next ss_Count
MsgBox Format((Timer - ss_BenchMark) / 86400, "hh:mm:ss")
End Sub
- After running the code, the command will show the time in a message box in hh:mm:ss format.
Read More: How to Create a Countdown Timer in Excel VBA
Things to Remember
- The Timer function can only be used in VBA.
Download Practice Workbook
Download the workbook.
VBA Timer Function.xlsm
[/wpsm_box]
Related Articles
- How to Create Timer Event with VBA in Excel
- How to Create Countdown Timer in Excel
- How to Create a Stopwatch in Excel