Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

I have a need to run a piece of code every 120 seconds. I am looking for an easy way to do this in VBA. I know that it would be possible to get the timer value from the Auto_Open event to prevent having to use a magic number, but I can't quite get how to fire off a timer to get something to run every 120 seconds.

I don't really want to use an infinite loop with a sleep if I can avoid it.


EDIT:

Cross-post based on an answer provided is at: Excel VBA Application.OnTime. I think its a bad idea to use this... thoughts either way?

like image 301
FinancialRadDeveloper Avatar asked Feb 23 '10 16:02

FinancialRadDeveloper


People also ask

How do I set a timer in VBA?

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.

How do I set macros to automatically run at a certain time?

If you need Excel to run some VBA at a specific time, or repeatedly at set intervals, you can use the Application. OnTime method. A basic call to Ontime requires that you supply a time when you want the code to run, and the name of the macro you want to run.

How do I set a delay in macro?

Select either the Timed delay in seconds or Timed delay in milliseconds option and then enter the number of seconds or milliseconds in the Delay Time edit box. üNote: This command suspends Macro Express for the amount of time specified.


1 Answers

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00") Application.OnTime alertTime, "EventMacro" 

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()     '... Execute your actions here'     alertTime = Now + TimeValue("00:02:00")     Application.OnTime alertTime, "EventMacro" End Sub 
like image 104
Alain Avatar answered Nov 07 '22 02:11

Alain