Применение функции 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 покажет время работы процедуры.
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
The VBA Timer function returns a Single numeric value representing the number of seconds elapsed since midnight on the current day.
If you want to pause code execution for duration of time check out the VBA Sleep and Application.Wait functions instead.
VBA Timer Function Syntax
The syntax for the Timer function in VBA is:
Timer()
The Timer function does not accept any parameters.
Example usage
The VBA Timer function can be used in VBA code. Let’s look at some VBA Timer function examples:
Measure elapsed time in Seconds
Debug.Print Timer() 'Result (at 11:55 AM): 42839,02 Dim startTime as Single startTime = Timer '... Some code here ... Debug.Print Timer - startTime 'Result: time in seconds elapsed
Measure elapsed time in Hours / Minutes / Seconds
As the VBA Timer function measures time elapsed in seconds, if we want minutes or hours instead we may need to tweak it:
Dim startTime as Single, timeElapsed as Single, hours as Long, min as Long, seconds as Single startTime = Timer 'Get current time '... Some code here ... timeElapsed = Timer - startTime 'Save the elapsed time to timeElapsed variable 'Extract hours hours = timeElapsed / 3600 timeElapsed = timeElapsed - hours * 3600 'Extract minutes mins = timeElapsed / 60 timeElapsed = timeElapsed - mins * 60 'Extract seconds seconds = timeElapsed Debug.Print "Time Elapsed: " & hours & " hours, " & mins & " minutes, " & seconds & " seconds"
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!
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
We had a post on the forum recently asking how to create a timer in Excel, to record how long things took to happen on a model railroad. You can use the same code to time anything of course, like how long your code is taking to execute.
A follow up request asked for code to count down to a date and/or time. So in this post I’m going to provide code that does both.
Update
Following a few requests, I modified the code so that the elapsed time does not reset to 0 when the timer is stopped then restarted.
This new code allows time to accumulate over multiple Start/Stop clicks. Download the code below
Enter your email address below to download the Excel workbook with the timer code.
By submitting your email address you agree that we can email you our Excel newsletter.
Timing Algorithm
For the countdown I’m going to use the Timer function which gives us the number of seconds elapsed since midnight.
Knowing that we’re basing our time calculation on the number of seconds since midnight, we don’t want to go past midnight whilst we’re timing something or our calculations will be wrong.
If you want to start timing something before midnight, and finish timing it after midnight, you could use NOW to work out time elapsed.
The algorithm for our code is:
Save StartTime While Stop button hasn't been pressed: Check elapsed time Display elapsed time on sheet (CurrentTime - StartTime) Display elapsed time on status bar When Stop button is pressed: Exit code
We can implement this as two subs. The first does the timing and display to the screen, the second sets a flag to indicate the Stop button has been pressed and the code should end.
These subs will be assigned to shapes so the shapes act as start and stop buttons.
The Stop button just sets a value in a cell. The timing sub monitors this cell until it sees the value that indicates it’s time to stop.
Here’s what the code looks like
You’ll notice I’ve actually written a third sub called ResetTimer which just resets cell A1 to 0:00:00. This isn’t really needed so you can remove it if you want.
Here’s what it looks like in action
I’ve included code that displays the elapsed time in the status bar as the timer is running
Application.StatusBar = ElapsedTime
When the timer is stopped the elapsed time is removed from the status bar
Application.StatusBar = False
If you don’t want to see the time on the status bar just remove these lines.
DoEvents
One thing we must do with code like this is use DoEvents.
When we call DoEvents it allows Excel to do other things, like check if the Stop button has been pressed.
If we just kept looping around displaying the elapsed time, Excel would hang.
Displaying the Elapsed Time
I’m using the format function to display the time as hh:mm:ss.
There are many formats you can use to display numbers, dates, times, serial numbers and strings, so read up on what the function can do.
NOTE: We have an in-depth guide if you want to learn about custom number formats.
Countdown
For the countdown code we need to (obviously) know the date/time we are counting down to. So I’ll read that in from a cell on the sheet and call it ZeroHour.
To work out the numbers of days, hours, minutes and seconds until then, just call the NOW() function and subtract one from the other:
ZeroHour = Range("A5").Value TimeDifference = ZeroHour - Now
By doing this we’ll end up with a time serial number stored in TimeDifference. If you aren’t sure what a time serial number is, read up on calculating time in Excel.
To display the time left we write it to a cell on the sheet, but we have to format it correctly first. As the value in TimeDifference is a time/date serial number it will look like 123.456.
If I just try to write that out to a cell, Excel will try to display the integer part (123) as the number of days since Jan 1st 1900. Of course we want to show the number of days from now until our target date.
To do this I use the INT() function to get rid of the decimal part of the serial number, which is the time, leaving me with just a number of days. I can then stitch all of this together like so:
Range("A6").Value = Int(TimeDifference) & "d " & Format((TimeDifference), "hh:mm:ss")
Times and Dates in the Past
If you try to use a time or date in the past, the VBA will catch this, display an error message and then exit.
Here’s what it looks like in action:
Download the Workbook
Click here to go back to the top of the page and get a copy of the code.
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Timer function (Visual Basic for Applications) |
vblr6.chm1009043 |
vblr6.chm1009043 |
office |
a39cf81a-a90c-5833-75e8-9ac4605e3b02 |
12/13/2018 |
medium |
Returns a Single representing the number of seconds elapsed since midnight.
Syntax
Timer
Remarks
In Windows, the Timer function returns fractional portions of a second. On the Macintosh, timer resolution is one second.
Example
This example uses the Timer function to pause the application. The example also uses DoEvents to yield to other processes during the pause.
Dim PauseTime, Start, Finish, TotalTime If (MsgBox("Press Yes to pause for 5 seconds", 4)) = vbYes Then PauseTime = 5 ' Set duration. Start = Timer ' Set start time. Do While Timer < Start + PauseTime DoEvents ' Yield to other processes. Loop Finish = Timer ' Set end time. TotalTime = Finish - Start ' Calculate total time. MsgBox "Paused for " & TotalTime & " seconds" Else End End If
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]