Применение функции Timer в VBA Excel для приостановки выполнения приложений и определения времени работы процедур. Примеры использования.
Timer – это функция без аргументов, которая возвращает количество секунд, прошедших после полночи. Значение типа Single.
На сайте разработчика сказано, что в Windows функция Timer возвращает дробные части секунды. О порядке дробной части там информации нет. Попробуем выяснить это сами, запустив в редакторе VBA Excel подпрограмму со строкой
MsgBox «Timer = « & Timer |
Исходя из результата, отображенного в информационном окне MsgBox, будем считать, что функция Timer возвращает сотые доли секунды. Во время экспериментов с процедурой Vremya из Примера 2 результат вычисления разницы между двумя значениями функции Timer достигал шести знаков после запятой, и один раз – семи.
Примеры использования в VBA Excel
Пример 1
Присвоение значения функции Timer переменной:
Пример 2
Код VBA Excel для приостановки приложений:
Dim Start As Single, Pause As Single Start = Timer Pause = 0.5 Do While Timer < Start + Pause DoEvents Loop |
- Start – переменная, в которую записывается первоначальное значение таймера.
- Pause – время в секундах (до сотых значений), на которое следует приостановить программу.
Функция DoEvents во время выполнения цикла передает управление операционной системе для обработки других событий. По рекомендации разработчиков не следует использовать DoEvents в тех случаях, когда
- приостановленная процедура может быть запущена повторно из другой части вашего кода;
- другие приложения могут обратиться к приостановленной процедуре.
Код для приостановки приложений можно использовать как отдельную подпрограмму, вставляя ее имя с указанием интервала в нужные места других процедур:
Sub StopSub(Pause As Single) Dim Start As Single Start = Timer Do While Timer < Start + Pause DoEvents Loop End Sub |
Проверяем работоспособность подпрограммы StopSub:
Sub Vremya() Dim x As Single x = Timer Call StopSub (3) MsgBox Timer — x End Sub |
Точный или почти точный результат будет только при использовании в качестве аргумента целых секунд, в том числе и в примере кода, предложенного разработчиком.
Такой способ приостановки приложений можно использовать в VBA Excel при создании бегущей строки.
Пример 3
Функцию Timer можно использовать для замера времени работы процедуры. Мы ее уже использовали для определения времени выполнения подпрограммы StopSub:
Sub Vremya() Dim x As Single x = Timer Call MySub MsgBox Timer — x End Sub |
Замените MySub на имя вашей подпрограммы и запустите код в редакторе VBA Excel. Информационное окно MsgBox покажет время работы процедуры.
VBA TIMER
Excel VBA TImer is used for detecting and calculating the time passed for completing any activity. In Excel VBA TIMER function can be used in many ways. We can calculate the time to complete any activity, we can calculate the time required to reach from start to end phase of any activity or even we can calculate the time required to click on any function as well.
This function cannot be performed in excel. In excel we can only see the time and add it to any cell but cannot measure it as Timer.
You can download this VBA TIMER Excel Template here – VBA TIMER Excel Template
Examples of VBA TIMER
Following are the different examples:
Example #1
In this example we will, how to count or measure time to run the completed code. For this go to insert menu of VBA and select a Module as shown below.
Once we do that, it will open a new module as shown below. Now in that write the Subcategory of current function name or any other name as per your choice.
Code:
Sub Timer1() End Sub
Now define two dimensions as Seconds1 and Seconds2 as a SINGLE function, which means there were two individual single number data (Without decimal).
Code:
Sub Timer1() Dim Seconds1 As Single Dim Seconds2 As Single End Sub
Now to Start the timer first select defined dimension Seconds1 and assign the function TIMER. And do the same thing for other dimension Seconds2 as shown below. The purpose of doing is to measure the start and end the time.
Code:
Sub Timer1() Dim Seconds1 As Single Dim Seconds2 As Single Seconds1 = Timer() Seconds2 = Timer() End Sub
This completes the timer portion of the code. Now we need to see the time lapse in running the code. For this, we need to print the output in the message box as shown below.
In below screenshot, we printed a text “Time taken:” and the difference between Seconds2 and Seconds1 with unit seconds.
Code:
Sub Timer1() Dim Seconds1 As Single Dim Seconds2 As Single Seconds1 = Timer() Seconds2 = Timer() MsgBox ("Time taken:" & vbNewLine & Seconds2 - Seconds1 & " seconds") End Sub
Once done, run the complete code by using F5 key or clicking on the play button as shown below.
We will see a message box with a counted time of 0 Seconds as the time required to run the complete code was 0.
We may see slightly more difference if the written code is huge.
Example #2
There is another method where we can choose a time lapse of any small amount as waiting time and let user or operator wait till the process gets completed. This can be used where we create a tool or macro with a huge line of code structure. By doing this we will allow the user to wait time whole code get to run, and operation is completed. Because doing something when the code is running may crash the file.
For this open a new module and write the Subcategory in the name of the required function or any name as shown below.
Code:
Sub Timer2() End Sub
Now to make this code small and simple we will use the inbuilt functions of VBA. And for this type Application followed a dot (.) and then from the list search and select Wait function as shown below.
This Wait function will allow us to add waiting time till the complete code may get run. This wait time is Boolean. After that consider the time when we run is 0 seconds with plus time we want to show as waiting time will be shown by TimeValue as shown below.
Code:
Sub Timer2() Application.Wait Now + TimeValue("00:00:10") End Sub
Here we consider 10 seconds as waiting time to complete the code run.
Now to print the waiting time we need to print the message in the message box with the help of command MsgBox as shown below.
Code:
Sub Timer2() Application.Wait Now + TimeValue("00:00:10") MsgBox ("Waiting Time - 10 Seconds") End Sub
As we can see, in message box we are added the text of “Waiting time – 10 Seconds” to be printed.
Now run code using F5 key or manually. We will see after we waited for 10 seconds, a message box will appear with the message used in the code.
Example #3 – VBA Timer
There is another easy way to see and show the current time in VBA. For this, we will directly use MsgBox and the rest of the code there only. For this open a new module in VBA and write Subcategory in the name of the used function or any other name as shown below.
Code:
Sub Timer3() End Sub
Now write MsgBox which is a command to print the message. In the bracket, we can write any message to be printed in the message box. Here we have chosen “Time is:” as our text and along with it “& Now ()” is used. It will display the current time with date in the pop-up message box.
Code:
Sub Timer3() MsgBox ("Time is : " & Now()) End Sub
Now in another message box, we will count the number of seconds passed in the whole day till current time by the clock. For this write MsgBox and between the brackets write the text “Timer is:” along with “& Timer ()” as shown below.
Code:
Sub Timer3() MsgBox ("Time is : " & Now()) MsgBox ("Timer is: " & Timer()) End Sub
Once done, run the code using the F5 key or manually. We will get two separate message boxes as shown below.
In the first message box, we will get the current date and time in DD/MM/YYYY and hh:mm:ss AM/PM format which is the default format Excel. In the second message box, we will see time lapsed in that day in seconds.
The second message box shows Timer is 59953.62 Seconds. If we divide that with 60 Seconds and 60 Minutes we will get the exact timer in hours lapsed in that day which is 16.65 Hours.
Things to Remember About VBA TIMER
- Always save the file in Marco Enabled Workbook to avoid loss of written VBA Code.
- Always compile the complete code step by step to make sure every code is incorrect.
- In example#1 SINGLE function is used to show the number as a whole. Even if we use DOUBLE it will give the result in decimal.
Recommended Articles
This has been a guide to Excel VBA TIMER. Here we discussed how to use VBA TIMER function along with some practical examples and downloadable excel template. You can also go through our other suggested articles–
- VBA On Error
- VBA Number Format
- VBA Find
- VBA TRIM
Return to VBA Code Examples
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:
Sub UsingTheVBATimerFunction()
Dim secondsSince As Single
secondsSince = Timer()
Debug.Print secondsSince
End Sub
The result is:
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:
Sub GettingTheActualTime()
Dim secondsSince As Single
Dim cTime As Double
Dim theActualTime As Variant
secondsSince = Timer()
cTime = secondsSince / (86400)
theActualTime = Format(cTime, "hh:mm:ss")
MsgBox "The time elapsed since midnight in seconds is" & " " & secondsSince & vbNewLine & _
"The actual time is:" & " " & theActualTime
End Sub
The result is:
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.
Sub BenchMark()
Dim Count As Long
Dim BenchMark As Double
BenchMark = Timer
'Start of Code to Test
For Count = 1 To 500000
Sheet1.Cells(1, 1) = "test"
Next Count
'End of Code to Test
MsgBox Timer - BenchMark
End Sub
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.
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!
Excel VBA TIMER Function
VBA Timer is an inbuilt function that gives us the fractional value of seconds. It is a very useful function used sometimes to pause any set of codes running or resume them based on the time provided by the user. In addition, one may use the Timer function as a statement in VBA with time input.
In simple terms, the TIMER gives the total number of seconds gone from midnight of the current day. Right from line one of the code, we can track the time consumed by our code to complete the process specified in the subprocedure.
Sometimes when you write a code. You want to test the code duration, i.e., the total time your code takes to complete the subprocedure. By testing the actual duration taken by your code, you can make your code efficient and eliminate the time-consuming process by deleting unwanted or long codes from your module.
Table of contents
- Excel VBA TIMER Function
- How to use the TIMER Function in VBA?
- Examples
- Example #1 – Calculate the Total Time Taken by your Code
- Example #2 – Show the Result in the Correct Time Format
- Example #3 – Alternative Code to Timer
- Things to Remember
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Timer (wallstreetmojo.com)
How to use the TIMER Function in VBA?
As we told you, the TIMER function returns the total seconds passed from midnight to the current date. So, when we write this article, the time is 13:50:45 in India.
We have created a Macro name and assigned the value of TIMER in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Code:
Sub Timer_Example1() MsgBox Timer End Sub
When we ran this code, we got the result of 50480.08.
The total seconds went past today’s midnight, i.e., from 12:00:00 AM.
So, from midnight to the current time, 14:01:20, a total of 14 hours, 1 minute, and 20 seconds have passed. Therefore, in seconds it is equal to 50480.08, given by our TIMER function.
Examples
You can download this VBA Timer Excel Template here – VBA Timer Excel Template
Example #1 – Calculate the Total Time Taken by your Code
Now, we will perform some simple coding to test the time the VBA takes to execute the procedure. But, first, we have written some code, as shown in the below image.
Code:
Sub Do_Until_Example1() Dim ST As Single ST = Timer Dim x As Long x = 1 Do Until x = 100000 Cells(x, 1).Value = x x = x + 1 Loop MsgBox Timer - ST End Sub
If we run this code now, it will show me the total time the VBA takes to execute.
It says 3.058594. The result given by this function is in seconds, i.e., the total time taken by this code is 3.058 seconds.
For you to use the code, we have written the below code for you.
Code:
Sub Timer_Example1() Dim StartingTime As Single StartingTime = Timer 'Enter your code here 'Enter your code here 'Enter your code here 'Enter your code here MsgBox Timer - StartingTime End Sub
Use the above and type your code after the code StartingTime = Timer, but before the code MsgBox Timer – StartingTime, i.e., in a green area, you need to enter your code.
Explanation: Firstly, the variable StartingTime = Timer means that the time of running the code equals the time elapsed from midnight to code running time.
Timer – StartingTime: After running the code, what is the time elapsed minus time recorded at the beginning of the code through the variable starting time?
It will give the difference between start and end time and return the result.
Example #2 – Show the Result in the Correct Time Format
As we have seen, the result given by the function is in seconds but not in a proper format. However, we can apply a VBA timeThe VBA time function returns the current time. This function has no arguments and returns the current system time. Thus, using this function, we can find the actual time taken by the line of codes to complete the process.read more format to the result using the FORMAT function.
Use the below code to see the result in the correct time format, i.e., “hh: mm: ss” format.
We have used the FORMAT function here. The result is given by (Timer – starting time). First, we divided it by the number 86400 to convert it to seconds as per time format rules. Then, we applied the time format in an hour, minute, and second format.
Now, if we run the code, it will give the result like this.
So, the total time taken by the code is 3 seconds.
The beauty of this code is the moment it crosses 60 seconds, it will show the result in minutes. So, we paused my code running for a minute (using Ctrl + Break) and saw the result.
So, the total time this code takes is 1 minute 2 seconds.
Example #3 – Alternative Code to Timer
There is an alternative to TIMER by using the NOW () function. Below is the alternative code.
Things to Remember
- The TIMER function will rest the value at the end of the day, i.e., at 11:59:59 PM.
- The NOW function returns the current date and current time.
- The TIMER function shows the total seconds gone past from the current date of midnight.
Recommended Articles
This article has been a guide to VBA Timer. Here, we learned how to use the Timer function in Excel VBA, its alternative function, and some simple to advanced examples. Below are some useful Excel articles related to VBA: –
- Excel VBA Progress Bar
- Formula of TIME in Excel
- Add Time in Excel
- Timeline in Excel
I needed a visible countdown timer that could stay on top of other windows and run smoothly whether making changes to the workbook, or minimizing the Excel window. So, I adapted the @don-kirkby’s creative code above for my own purposes and figured I’d share the result.
The code below requires creation of a module and a userform as noted in the comments, or you can download the .xlsm
at the bottom of this answer.
I used the Windows Timer API for more accurate and smooth countdown (and also customizable down to ~100 millisecond timer resolution, depending on your processor. There’s even a «tick tock» sound. ⏰
Insert a new module and save it as modUserFormTimer
. Add two form control command buttons to the worksheet, labelled Start Timer and Stop Timer and assigned procedures btnStartTimer_Click
and btnStopTimer_Click
.
Option Explicit 'modUserFormTimer
Public Const showTimerForm = True 'timer runs with/without the userform showing
Public Const playTickSound = True 'tick tock (a WAV sounds could be embedded: `https:// goo.gl/ ReuUyd`)
Public Const timerDuration = "00:00:20" 'could also Insert>Object a WAV for tick or alarm
Public Const onTimerStart_MinimizeExcel = True 'minimize Excel? (countdown remains visible)
Public Const onTimerStart_MaximizeExcel = True 'maximize Excel when timer completes?
'timer could be on top of other applications; instructions here: `https:// goo.gl/ AgmWrM`
'safe for 32 or 64 bit Office:
Private Declare PtrSafe Function SetTimer Lib "User32" (ByVal hWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As LongPtr) As Long
Private Declare PtrSafe Function KillTimer Lib "User32" (ByVal hWnd As Long, ByVal nIDEvent As Long) As Long
Public Declare PtrSafe Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Public schedTime As Date 'this is the "major" timer set date
Private m_TimerID As Long
Public Sub OnTimerTask()
'the procedure that runs on completion of the "major timer" (timer won't reschedule)
Unload frmTimer
''''''''''''''''''''''''''''''
MsgBox "Do Something!" ' < < < < < Do Something Here
''''''''''''''''''''''''''''''
End Sub
Public Sub btnStartTimer_Click()
schedTime = Now() + TimeValue(timerDuration)
InitTimerForm
End Sub
Public Sub btnStopTimer_Click()
'clicking the 'x' on the userform also ends the timer (disable the close button to force continue)
schedTime = 0
frmTimer.UserForm_Terminate
End Sub
Public Sub InitTimerForm()
'run this procedure to start the timer
frmTimer.OnTimer
Load frmTimer
If showTimerForm Then
If onTimerStart_MinimizeExcel Then Application.WindowState = xlMinimized
frmTimer.Show 'timer will still work if userform is hidden (could add a "hide form" option)
End If
End Sub
Public Sub StartTimer(ByVal Duration As Long)
'Begin Millisecond Timer using Windows API (called by UserForm)
If m_TimerID = 0 Then
If Duration > 0 Then
m_TimerID = SetTimer(0, 0, Duration, AddressOf TimerEvent)
If m_TimerID = 0 Then
MsgBox "Timer initialization failed!", vbCritical, "Timer"
End If
Else
MsgBox "The duration must be greater than zero.", vbCritical, "Timer"
End If
Else
MsgBox "Timer already started.", vbInformation, "Timer"
End If
End Sub
Public Sub StopTimer()
If m_TimerID <> 0 Then 'check if timer is active
KillTimer 0, m_TimerID 'it's active, so kill it
m_TimerID = 0
End If
End Sub
Private Sub TimerEvent()
'the API calls this procedure
frmTimer.OnTimer
End Sub
Next, create a userform, save it as frmTimer
. Add a text box named txtCountdown
. Set property ShowModal
to False
. Paste the following into the form’s code window:
Option Explicit 'code for userform "frmTimer"
'requires a textbox named "txtCountdown" and "ShowModal" set to False.
Dim nextTriggerTime As Date
Private Sub UserForm_Initialize()
ScheduleNextTrigger
End Sub
Public Sub UserForm_Terminate()
StopTimer
If schedTime > 0 Then
schedTime = 0
End If
If onTimerStart_MaximizeExcel Then Application.WindowState = xlMaximized 'maximize excel window
Unload Me
End Sub
Private Sub ScheduleNextTrigger() 'sets the "minor" timer (for the countdown)
StartTimer (1000) 'one second
End Sub
Public Sub OnTimer()
'either update the countdown, or fire the "major" timer task
Dim secLeft As Long
If Now >= schedTime Then
OnTimerTask 'run "major" timer task
Unload Me 'close userForm (won't schedule)
Else
secLeft = CLng((schedTime - Now) * 60 * 60 * 24)
If secLeft < 60 Then 'under 1 minute (don't show mm:ss)
txtCountdown = secLeft & " sec"
Else
'update time remaining in textbox on userform
If secLeft > 60 * 60 Then
txtCountdown = Format(secLeft / 60 / 60 / 24, "hh:mm:ss")
Else 'between 59 and 1 minutes remain:
txtCountdown = Right(Format(secLeft / 60 / 60 / 24, "hh:mm:ss"), 5)
End If
End If
If playTickSound Then Beep 16000, 65 'tick sound
End If
End Sub
Download the demo .xksm.
here. There are numerous ways this can be customized or adapted to specific needs. I’m going to use it to calculated and display real time statistics from a popular Q&A site in the corner of my screen…
Note that, since it contains VBA macro’s, the file could may set off your virus scanner (as with any other non-local file with VBA). If you’re concerned, don’t download, and instead build it yourself with the information provided.)