Excel vba time running

Содержание

  1. VBA Timer Function
  2. Using the VBA Timer Function
  3. Use VBA Timer to get Actual Time
  4. Time a Section of VBA Code
  5. VBA Coding Made Easy
  6. VBA Code Examples Add-in
  7. VBA Timer
  8. Excel VBA TIMER Function
  9. How to use the TIMER Function in VBA?
  10. Examples
  11. Example #1 – Calculate the Total Time Taken by your Code
  12. Example #2 – Show the Result in the Correct Time Format
  13. Example #3 – Alternative Code to Timer
  14. Things to Remember
  15. Recommended Articles
  16. VBA Excel. Функция Timer (примеры)
  17. Описание функции Timer
  18. Примеры использования в VBA Excel
  19. 3 комментария для “VBA Excel. Функция Timer (примеры)”
  20. How do you test running time of VBA code?
  21. 9 Answers 9
  22. Timer or Stopwatch in Excel VBA
  23. Download Excel Workbooks
  24. Timing Algorithm
  25. DoEvents
  26. Displaying the Elapsed Time
  27. Countdown
  28. Times and Dates in the Past
  29. Download the Workbook
  30. More Excel VBA Posts
  31. Display All Matches from Search in Userform ListBox
  32. Animating Excel Charts
  33. Dynamic Data Validation Lists in Userforms
  34. Show Report Filter Pages for Power Pivot PivotTables
  35. Charting Real Time Data in Excel
  36. Select Multiple Items from Drop Down (Data Validation) List
  37. Multi-Language Excel Calendar (Date Picker) for Worksheets and Userforms
  38. Automating and Emailing Pivot Table Reports
  39. Searching for Data With a User Form
  40. Checking Values in Range Objects With VBA
  41. Reader Interactions
  42. Comments

VBA Timer Function

In this Article

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:

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:

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.

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!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Timer

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

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article 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.

Code:

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

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:

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:

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

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: –

Источник

VBA Excel. Функция Timer (примеры)

Применение функции Timer в VBA Excel для приостановки выполнения приложений и определения времени работы процедур. Примеры использования.

Описание функции Timer

На сайте разработчика сказано, что в Windows функция Timer возвращает дробные части секунды. О порядке дробной части там информации нет. Попробуем выяснить это сами, запустив в редакторе VBA Excel подпрограмму со строкой


Исходя из результата, отображенного в информационном окне MsgBox, будем считать, что функция Timer возвращает сотые доли секунды. Во время экспериментов с процедурой Vremya из Примера 2 результат вычисления разницы между двумя значениями функции Timer достигал шести знаков после запятой, и один раз – семи.

Примеры использования в VBA Excel

Пример 1
Присвоение значения функции Timer переменной:

Пример 2
Код VBA Excel для приостановки приложений:

  • Start – переменная, в которую записывается первоначальное значение таймера.
  • Pause – время в секундах (до сотых значений), на которое следует приостановить программу.

Функция DoEvents во время выполнения цикла передает управление операционной системе для обработки других событий. По рекомендации разработчиков не следует использовать DoEvents в тех случаях, когда

  • приостановленная процедура может быть запущена повторно из другой части вашего кода;
  • другие приложения могут обратиться к приостановленной процедуре.

Код для приостановки приложений можно использовать как отдельную подпрограмму, вставляя ее имя с указанием интервала в нужные места других процедур:

Проверяем работоспособность подпрограммы StopSub:

Точный или почти точный результат будет только при использовании в качестве аргумента целых секунд, в том числе и в примере кода, предложенного разработчиком.

Такой способ приостановки приложений можно использовать в VBA Excel при создании бегущей строки.

Пример 3
Функцию Timer можно использовать для замера времени работы процедуры. Мы ее уже использовали для определения времени выполнения подпрограммы StopSub:

Замените MySub на имя вашей подпрограммы и запустите код в редакторе VBA Excel. Информационное окно MsgBox покажет время работы процедуры.

3 комментария для “VBA Excel. Функция Timer (примеры)”

Здравствуйте, Евгений! Здравствуйте, коллеги!
Помогите, пожалуйста, разобраться. Положенные сутки в одиночку продумал 🙂
Задача: в UserForm нужно подсветить контрол SpinButton1 при событии Change, изменив на 2с его фон .BackColor, после 2с вернуть .BackColor на начальный. Код ниже.
Код не работает в смысле назначения – изменения .BackColor на экране. При этом Debug’и исправно выдают коды будто бы изменённых цветов, и раскомментированный любой MsgBox тоже приводит к искомой покраске контрола.
Добавление DoEvents: перед Loop тоже приводит к нужной покраске на экране, но возникает дребезг, т.е. срабатыванию Change 2-3 раза при одном нажатии.
Что в коде не так, и в каком направлении думать, если данный код почему-то не имеет права на существование?

Источник

How do you test running time of VBA code?

Is there code in VBA I can wrap a function with that will let me know the time it took to run, so that I can compare the different running times of functions?

9 Answers 9

Unless your functions are very slow, you’re going to need a very high-resolution timer. The most accurate one I know is QueryPerformanceCounter . Google it for more info. Try pushing the following into a class, call it CTimer say, then you can make an instance somewhere global and just call .StartCounter and .TimeElapsed

10ms accuracy, @Kodak’s answer below gives the same thing in one line of code (importing GetTickCount from kernel32).

The Timer function in VBA gives you the number of seconds elapsed since midnight, to 1/100 of a second.

If you are trying to return the time like a stopwatch you could use the following API which returns the time in milliseconds since system startup:

after http://www.pcreview.co.uk/forums/grab-time-milliseconds-included-vba-t994765.html (as timeGetTime in winmm.dll was not working for me and QueryPerformanceCounter was too complicated for the task needed)

For newbees, these links explains how to do an automatic profiling of all the subs that you want to time monitor :

As Mike Woodhouse answered the QueryPerformanceCounter function is the most accurate possible way to bench VBA code (when you don’t want to use a custom made dll). I wrote a class (link https://github.com/jonadv/VBA-Benchmark) that makes that function easy to use:

  1. only initialize the benchmark class
  2. call the method in between your code.

There is no need to write code for substracting times, re-initializing times and writing to debug for example.

This would automatically print a readable table to the Immediate window:

Ofcourse with only one piece of code the table isnt very usefull, but with multiple pieces of code, it instantly becomes clear where the bottleneck in your code is. The class includes a .Wait function, which does the same as Application.Wait, but requires only an input in seconds, instead of a time value (which takes a lot of characters to code).

Prints a table with percentages and summarizes code with the same name/tag:

Источник

Timer or Stopwatch in Excel VBA

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.

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.

Download Excel Workbooks

Time Resets to 0 When Stopped and Restarted Timer-Stopwatch.xlsm

Time Accumulates When Stopped and Restarted Timer-Stopwatch1.xlsm

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:

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

When the timer is stopped the elapsed time is removed from the status bar

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:

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:

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.

More Excel VBA Posts

Display All Matches from Search in Userform ListBox

Animating Excel Charts

Dynamic Data Validation Lists in Userforms

Show Report Filter Pages for Power Pivot PivotTables

Charting Real Time Data in Excel

Select Multiple Items from Drop Down (Data Validation) List

Multi-Language Excel Calendar (Date Picker) for Worksheets and Userforms

Automating and Emailing Pivot Table Reports

Searching for Data With a User Form

Checking Values in Range Objects With VBA

Reader Interactions

Great Timer.
Quick Question, hopefully this sub is not dead, Is there a way for the timer to continuously countdown without having to click start or Stop?

Thanks Matt. You need some event to start/stop the timer. You could write a macro that starts the timer when the workbook opens and then you could stop it after a set period of time or maybe at a set time.

If you have a specific problem you could post it on our forum and we can help out there.

Hi. That’s so great. I would like to be able to pause the stopwatch and restart with the current time elapsed. For example, I hit start. Then, after 1 minute, I want to pause so I hit pause. Then, a few minutes later, I hit resume and the time will resume from 1 minute and so on.

Could you please tell me the lines I need to add please?
Here is the code:

Dim Start As Single, RunTime As Single
Dim ElapsedTime As String

Sheets(“New”).Range(“C1”).Value = 0
Sheets(“New”).Range(“B1”).Interior.Color = 5296274 ‘Green
Start = Timer ‘ set start time.
Debug.Print Start
Do While Sheets(“New”).Range(“C1”).Value = 0

DoEvents
RunTime = Timer
ElapsedTime = Format((RunTime – Start) / 86400, “hh:mm:ss”)

Sheets(“New”).Range(“B1”).Value = ElapsedTime
Application.StatusBar = ElapsedTime

Sheets(“New”).Range(“B1”).Value = ElapsedTime
Sheets(“New”).Range(“B1”).Interior.Color = 192 ‘Dark red
Application.StatusBar = False

I had to make changes in a few different places in order to get this working – please download this file to see the new working code.

fab code. just what i needed. simple and works almost perfectly…
unfortunately the timer blocks all further work on the data sheet while it’s running.
any ideas how to fix that?

sorry team, i just saw that i am not the only one with the problem. yes, i had already chosen the option to put start time in one cell and end time in another and to calculate the difference. i need to have a running timer on screen tho. i can’t see from the other comments whether anyone found a solution.

When a cell is in edit mode, no code can run unfortunately.
You can try a modal form, opened in a different excel instance, will allow you to have the userform timer while you edit the other instance workbook sheet.
The only way to have code running and sheet editing is if the excel instance are not the same. It’s a complex scenario though.

I am a rookie in VBA. But I was wondering. Would it be possible to add a -20 seconds button and a + 20 seconds button?

Hi Ruben,
Not sure how you want it to work, but keep in mind that the code will just compare the start time with the time when you press the stop button.
You can change the calculation for ElapsedTime: (RunTime-Start+TimeSerial(0,0,20)) to add 20 seconds to the difference.

Thank you Catalin, your suggestion is a good idea but I would prefer to see the time running while I’m completing the table and not only to see the start time and the final one. Do you think it could be possible? Thank you

Hi Simone,
See this discussion, there is no real workaround. While you edit a cell, no code will run.
Default windows timer is not an option?
If you search your computer for Alarms & Clock, there is a windows app with this name. It includes a stopwatch and a countdown timer.
It might work though, if you design a crazy flow like: use the code to display timer in a modeless userform instead of cells, then in your current file you are working on write code to open the timer file in a separate new instance of excel, that will be completely independent. In 2 separate instances of excel, 2 different codes can run in the same time, it’s not possible in the same instance.

Thank you Catalin for your suggestions
Regards
Simone

Good morning, the timer stops when I edit a number or a character in a cell. I believed that the command DoEvents would avoid this but I was wrong, can you please help me?
Thank you
Simone

Hi Simone,
Can you explain what are you trying to achieve?
When a cell is in edit mode, no code can run, therefore OnTime will fail.
Maybe there’s another way, if you can clarify the needs.

Hi Catalin, thank you for your reply. I should start the timer and in the meantime edit in the cells but unfortunately I found that as soon as I edit in a cell the timer stops. Is there a way to solve this?
Thank you
Simone

Why do you need the timer? What things needs to be measured?

I need to take the time I spent to complete a table in Excel. So the target is to start the timer, to complete the table by adding the proper numbers in the cells and finally to stop the time when I completed the table. Is it possible?
Thank you

My guess is that you don’t need a timer for that.
The start button should just fill in a cell the start time, same for stop button, should put in the next cell the time when you press the button.
You will end up with the 2 dates-times you need.

I’m trying to duplicate a count up & down timer based on a reference time to count up/down to..

For example my reference time is 10 minutes. One timer will count the elapsed time from 10 min. the other timer will tell me time remaining.
For example: reference time is 10 minutes, and 3 minutes have passed. Elapsed time will show 3 minutes. Remaining timer will show 7 minutes. Both values are positive.
I have downloaded several countdown timers, however, I have not solved the time remaining timer.

You only need to set up 1 VBA timer in this scenario. If this timer is counting the elapsed time then in another cell you have (10 minutes – elapsed time) to give you time remaining.

Is there a way to insert vertical alignment lines for easy following between If & End If or Sub & End Sub etc. as in your code?

Not in the VBA editor. Those images are taken from inside VS Code. I put the VBA in there just to take those images. I wish Microsoft would improve the VBA editor.

This code is useful . But I want to take in user input while the timer runs. The timer stops anytime I try to type something in the worksheet

Can you please help me with that

Sorry Susanna, if you try to enter something to the sheet Excel will stop the VBA from running.

You could write your code to take user input from a msgbox or a userform while the timer us running though.

In the example code I see:
*****
Dim counter As Long

counter = 0
*****
But then I don’t see counter referenced elsewhere in the code. Just extra lines or was this intended to be part of the algorithm?

That piece of code is in the image which I must have taken before removing counter. If you download the workbook you’ll see that counter isn’t in there. I’ll have to update the image.

Hi,
Is it possible that when this excel be “shared” and opened, for example I will use this file for a game by which all users have access to the excel file with the timer. so if I click start, all the user will simultaneously see the countdown on their own PC. and when I do an action like stop, it will also make the countdown stop for the other users?

Short answer: No.
It may be possible to save a text file in a folder that may be sync’d to a cloud storage where everyone has access to, like OneDrive, Google Drive, Dropbox, but there are some times needed for sync agents to detect a change in a file, upload it to cloud, then other computers sync agents need time to detect a change in cloud and download it to user computer. Will never show instantly on other computers, there will be a delay from the moment there is a time change until that change reaches other computers. But when you stop the clock, that final value will be what they see, even if not in real time (after a few seconds).

Hi,
Thanks for the help.
In your example, is it possible to have a pre-defined number of minutes for the timer to countdown rather than having to check a cell?

ZeroHour = “Xminutes”.Value
TimeDifference = ZeroHour – Now

Hi Claude,
You can try to set Start=Now():
Start=Now()
Do Until Now() >= Start+TimeSerial(0,5,0)
The loop will end when the current time is equal or higher than start time + 5 minutes.

Excellent code that works well, but I do have a question. Say I wanted to start a timer at the start of a multi-day event. Would it be possible to start a timer on a document on my computer, save the document, exit the document, and email or send it to others or put it in a share drive, and have it constantly keep running and display the same accurate running timer across all other copies on other computers for other users? Any help would be greatly appreciated.

Hi Josiah,
I’m afraid that there is no easy answer for that, there is no connection between computers if they are in different locations, but there is always a workaround. If you put the file in a shared cloud storage folder, the code can be modified to store the times in text files for each computer running the file, and the code can also collect all text files created by all computers (each file will have computer name in file name, so each file should have different file names).
There will be a delay between the moment when the time is stored in the text file and the moment when cloud sync agent detects a change and downloads the updated text files, this delay depends on sync agent, internet speed, computer speed, and so on.

I am new to vba and have downloaded the your file. I am trying the above code to show the elapsed time. Upon adding the vba code at the end of the existing code, I am getting an error. I have added sheet2 to on the workbook.

Your response is greatly appreciated.

I’ll need to see your code to figure out what is going wrong. Please open a topic on the forum and post your workbook there.

I really like this code. However, it lacks 2 elements of a real ‘stopwatch’.
1) When you Pause the clock, then re-Start the clock, the time has not paused, but instead has kept running. So, by starting it back, we have not really Stopped the clock, only Paused to see the time when Stop was pressed.
2) When you press Reset, then Start, it doesn’t start over at 0:00. Instead it takes up where it left off when you pressed Pause.

Also, there needs to be a way to count down as well as count up.

I’ve been trying to ‘fix’ these issues but find my VBA skills lacking. Will you help me make this a really great stopwatch?! Thanks.

Hi Michael,
Please use our forum to upload your sample file with code, It will be much easier to help you.
Just create a new topic after sign-in.

Thanks for the code, cheers. I am trying to add sound to it, when the timer has reached the elapsed time. Any tip or trick how to do it? I need to alert people whenever it happens

Hi,
Have you tried this code?
Beep
You can add it multiple times, like Beep: Beep: Beep

Thank you for sharing! If you wouldn’t mind providing feedback on the following application of your template- see below. The basics: when green the timer stops and resets, when red the timer begins to count/ collect time- displaying the running value in the cell. Currently the program only counts displays up to one second before terminating.

Range(“A937”).Select
If ActiveCell.Interior.Color = 16777215 Then
ActiveCell.Interior.Color = 5287936
ElseIf ActiveCell.Interior.Color = 5287936 Then
ActiveCell.Interior.Color = 255
ElseIf ActiveCell.Interior.Color = 255 Then
ActiveCell.Interior.Color = 5287936
End If

Dim Start As Single, RunTime As Single
Dim ElapsedTime As String
Dim Counter As Long
Range(“A937”).Value = 0
If Range(“A937”).Interior.Color = 255 Then
Counter = 0
Start = Timer

Debug.Print Start
Do While Range(“A937”).Value = 0
DoEvents
RunTime = Timer
ElapsedTime = Format((RunTime – Start) / 86400, “hh:mm:ss”)
Range(“A937”).Value = ElapsedTime
Application.StatusBar = ElapsedTime
Loop
Range(“A937”).Value = ElapsedTime
ElseIf Range(“A937”).Interior.Color = 5287936 Then
Range(“A937”).Value = 1
ElseIf Range(“A937”).Value > 0 Then
Range(“A937”) = Format(0, “hh:mm:ss”)

When I run this code it does this the first time:

1. Changes the ActiveCell to green
2. Changes the value of the ActiveCell to 0
3. Checks if the AC is red (it isn’t)
4. Checks if the AC is green – it is so it sets the AC value to 1
5. End of Sub

The next time I run it it does this

1. Checks if the AC is green – it is, so it changes it to red
2. Sets the AC to 0
3. Checks if the AC is red – it is so it enters the Do While loop
4. Sets the AC to ElapsedTime and then exist the Do While because the AC is no longer 0

The 3rd time I run it it does this

1. Checks if the cell is red – it is, so it changes it to green
2. Sets the AC to 0
3. Checks if the AC is red – it isn’t
4. Checks if the AC is green – it is so it sets the value of the AC to 1

So it is doing what it is coded to do. I’m not sure what you actually want it to do?

If you use F8 to step through the code, which is what i did, you can see what it is doing.

You can read this topic about debugging VBA

If you need any more help with this, please post a topic on the forum and supply your entire workbook.

Hello, Thank you for this beautiful elapsed time code. I am a beginner in vba macros and just learning by errors. I have used your elapsed time loop in the beginning of my script and the problem is that the code is stuck in the do While time loop and not executing the next lines of codes. Is there any way to run this loop while other codes are getting executed at the same time?

Hi Pratik,
Only one code can run at a time. Multiple codes can run in the same time only if each code is running from its own excel instance.
The Timer code can store data to registry, all other codes should contain code to look into registry to display that timer value.
If you want to go this way, you should open a new topic on our forum, you can upload there sample files and codes.

While the time is running I need to insert some values in the same worksheet. If I do this, time will run out. Is there any way to make this possible?

When you type something into a cell and enter Edit mode, Excel stops running the macro. That’s just the way it works.

Depending on what it is you are entering though, could you build a macro to take user input and then write that to the sheet? This way the macro keeps running and the timer keeps timing.

Love the stopwatch. Is it possible to add some code so it would create a historical copy of time elapsed for each start and stop event

Hi Joe,
Anything can be done. Instead of displaying the result, just save it in a new row in a separate sheet. Add this code at the end of your existing code:

Dim Wks As Worksheet, NextRow As Long
Set Wks = ThisWorkbook.Worksheets(«Sheet2»)
NextRow = Wks.Cells.Find(What:=»*», After:=Wks.Cells(1), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
ThisWorkbook.Worksheets(«Sheet2»).Cells(NextRow, «A») = Start
ThisWorkbook.Worksheets(«Sheet2»).Cells(NextRow, «B») = ElapsedTime

hi, i adding it at the end of the code but it gives an error as invalid procedure for the set wks line

Do you have a sheet called Sheet2?

Please open a topic on the forum and post your code in there so we can see what you have.

I have a sample file and would like to run multiple timers at the same time. How would I be able to tweak this code to meet my needs?

Unfortunately with VBA you can’t have multiple bits of code running at the same time, it is single threaded.

Can anyone recommend how I can go about adding the functionality of starting and stopping the clock automatically when I open or close the workbook it is contained in.

Hi Mike,
All you have to do is to use the Workbook_Open & BeforeClose events from ThisWorkbook module, just add StartTimer in Open event and StopTimer in the BeforeClose event:
Private Sub Workbook_Open()
StartTimer
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
StopTimer
End Sub

Hello
I downloaded this workbook and the Timer runs fine on the relevant sheet. Great job!

I now added as a module. If I call StartTime via the Workbook.Open event it grey’s out my Home Menu tabs until i stop the timer.
Any idea why this happens?

Are you using DoEvents ?

It’s hard to say what’s going on without seeing your code. You could open a topic on our forum and attach your workbook so I can take a look.

Never really used macros before so how can I copy the stopwatch to have several of them on one sheet?

Hi Ry,
You need to copy the StartTimer and ResetTimer Procedures as many times you need, rename each copy StartTimer1 and ResetTimer1, StartTimer2 and ResetTimer2, and so on. Change the cell references in these new procedures as needed, from Range(“A1”) and Range(“C1”) to the cells you want. You will also need to copy the buttons from sheet, and assign to them the new macros: right click the shape-Assign Macro-choose the procedure from list.
Of course, you cannot have more than 1 timer procedure running at a time.
Catalin

I already do the procedure you tell for me to have multiple timer on single sheet .. but the problem is the 1st timer stop when the second timer is running ..its like they are displaying one single timer

Hi Mark,
Already mentioned that only one code can run.
We’ll continue on forum, if you can provide a sample file and details.
Catalin

I tried to change Format(elapsed time,”hh:mm:ss”) to Format(elapsed time,”mm:ss”) and Format(elapsed time,”ss”) in case the elapsed time is less than 1 hour or even 1 min only in order to keep a concise time format. Unfortunately the calculation was just cycling the second portion and displayed the number of min as a fixed number, say “12”. Could you please tell me what’s wrong? Thanks very much.

Hi Julian,
Hard to say without seeing your file. Can you upload on our forum a sample file with your code, so we can see your data type? Create a new topic after sign-in, we’ll see what’s wrong.

Is it possible to show up unlimited minutes like in XNote Stopwatch? I mean 123:45 for example.

Yes,
The cell should have this custom format: [h]:mm
Cheers,
Catalin

This is wonderful! I think I will be able to use this at work for setting standards.

Glad you find it useful.

i’d like to modify this to display the number of days remaining to elect to purchase something. is it possible with this?

Hi Deb,
Yes, anything is possible.
TimeStart should be stored in a cell in this case, because I doubt that the macro will run 30 days or less. It should look like:
ThisWorkbook.Worksheets(“Sheet1”).cells(1)=Date
Then, the TimeStop should be :
TimeStop=Date
Next, the final evaluation should be:
Msgbox 30-(TimeStop-CDate(ThisWorkbook.Worksheets(“Sheet1″).cells(1))) & ” Days left!”

I’ve seen another countdown timer displayed the remaining days / hours / minutes / seconds. Could you please also provide a sample file to demonstrate it? It would be perfect.

Sorry this reply has taken a while, I had to write new code for this.

I’ve updated the post and the workbook, so download the workbook and you’ll find the new code for the countdown in there.

I do appreciate your effort to work out the new code for me. However, it seemed something wrong with the download link. Could you please fix it at your convenience. Thanks again.

Источник

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:

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:

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:

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.

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!
vba save as

Learn More!

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

vba timer stopwatch code

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

vba timer stopwatch code working with status bar display

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:

VBA countdown timer

Download the Workbook

Click here to go back to the top of the page and get a copy of the code.

What This VBA Code Does

There are various scenarios where you may want to calculate the time it takes for your VBA code to run.  I often do this when trying to test various ways to code a procedure. I like to see which method gives me a faster run time.  Below is some simple snippets you can add to the beginning and end of your VBA code to report out how long the procedure took to run.

Display Calculation In Seconds

Display Calculation In Minutes

For Bottleneck Testing

If you need a very specific timing mechanism to determine bottlenecks in your code, there is a VBA function that was written by Charles Williams called the MicroTimer.  To learn more about this function, you can view the code here.

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris
Founder, TheSpreadsheetGuru.com

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

VBA Timer

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

vba timer example 1

When we ran this code, we got the result of 50480.08.

vba timer example 1.1

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

vba timer example 2.1

If we run this code now, it will show me the total time the VBA takes to execute.

vba timer example 2.2

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

vba timer example 2.3

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.

example 3.1

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.

example 3.2

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.

example 3.3

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.

example 4

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

Like this post? Please share to your friends:
  • Excel vba абсолютная ссылка в excel
  • Excel vba time from date
  • Excel vba xlsm xlsx
  • Excel vba time formats
  • Excel vba worksheetfunction trim