Excel VBA: Run Macro Every X Minutes
In this article
To run a macro every X minutes in Excel, use Application.OnTime to schedule the next run each time the macro finishes. The shortest working setup is: put your code in a normal module, add a scheduler sub that calls Application.OnTime Now + TimeValue("00:05:00"), "MyMacro", and have MyMacro call the scheduler again at the end so it re-arms itself. Because OnTime schedules a single future event, the loop only continues if each run books the next one. This guide shows the exact code, how to start and stop it safely, and the mistakes that make it fire twice or stop silently.
What You'll Need
- Excel on Windows or Mac with macros enabled (a .xlsm workbook).
- The Developer tab visible: File > Options > Customize Ribbon > tick Developer. On Mac, Excel > Preferences > Ribbon & Toolbar.
- Macro security set to allow macros, at least for this workbook. Trust Center settings live under File > Options > Trust Center > Trust Center Settings > Macro Settings on Windows; on Mac, Excel > Preferences > Security.
- Your macro already written and tested once by hand, so you know it works before scheduling it.
Menu labels can differ slightly by Excel version, platform and region, so treat the paths above as a guide rather than exact wording.
Step-by-Step
- Open the VBA editor. Press Alt+F11 on Windows, or Option+F11 on Mac. In the Project pane, right-click your workbook and choose Insert > Module. A normal module is the right place for scheduling code; code behind a sheet or ThisWorkbook can work too, but a standard module keeps things easy to find.
- Write your worker macro. This is the code that actually does the job. Keep it short and make sure it cannot show a modal dialog or wait for user input, because a blocked macro stops the schedule from re-arming. For example:
Sub MyTask() ' your code here ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Now End Sub - Add the scheduler sub. This books the next run. Put the interval in one place so it is easy to change:
ThePublic NextRun As Date Sub StartSchedule() NextRun = Now + TimeValue("00:05:00") Application.OnTime EarliestTime:=NextRun, _ Procedure:="RunAndReschedule", Schedule:=True End SubTimeValue("00:05:00")means five minutes. Use"00:00:30"for thirty seconds,"01:00:00"for an hour. - Make the worker re-arm itself. The scheduled procedure must call the scheduler again at the end, otherwise it runs once and stops:
TheSub RunAndReschedule() On Error GoTo Cleanup MyTask Cleanup: StartSchedule End SubOn Errorline matters: ifMyTaskerrors, the cleanup block still books the next run, so one bad run does not kill the loop. - Add a stop sub. Without this you cannot cancel a pending run except by closing Excel:
TheSub StopSchedule() On Error Resume Next Application.OnTime EarliestTime:=NextRun, _ Procedure:="RunAndReschedule", Schedule:=False On Error GoTo 0 End SubSchedule:=Falseargument cancels the booked run. TheOn Error Resume Nextprevents an error if nothing is currently scheduled. - Run
StartScheduleonce. Place the cursor inside it and press F5, or use Run > Run Sub/UserForm. From that moment the macro fires every five minutes until you runStopScheduleor close Excel. - Optionally start it automatically. To begin when the workbook opens, put
StartSchedulein the ThisWorkbook module'sWorkbook_Openevent. AddStopScheduletoWorkbook_BeforeCloseso a pending run does not try to reopen the file after it is closed.
Common Mistakes
- Scheduling the worker directly.
Application.OnTime ..., "MyTask"runs once. The re-arm has to happen inside the scheduled procedure, not only at the start. - Booking a new run without cancelling the old one. Calling
StartScheduletwice creates two independent chains, so the macro fires twice as often. Always cancel with the storedNextRuntime before re-scheduling. - Losing the scheduled time. If
NextRunis a local variable instead of a module-levelPublicone,StopSchedulehas nothing to cancel and the run cannot be stopped. - Blocking dialogs.
MsgBox,InputBox, or a prompt inside the worker halts Excel and the next booking never happens. Log results to cells instead. - Forgetting that
OnTimeis per Excel instance. Closing the workbook or Excel cancels all pending runs. There is no background service that keeps firing when Excel is shut.
Tips
- Store the interval in a named constant or a cell so you can change it without editing code.
- Guard against overlapping runs: if a run can take longer than the interval, set a flag at the start of
MyTaskand skip the next booking while it is set. - Use
Application.OnTimewith a specific time (for example 09:00) rather than an interval when you want a fixed daily run. - Keep the worker idempotent: writing the same value twice should not corrupt data, in case a run is duplicated.
- Test with a one-minute interval first, then lengthen it once you have seen it re-arm correctly.
Troubleshooting
If the macro never fires, check that macros are enabled for the workbook and that you actually ran StartSchedule; pressing F5 on the worker only runs it once. If it fires once and stops, the re-arm call is missing or is being skipped because of an error before it, so add the On Error GoTo Cleanup pattern shown above. If it fires twice as often as expected, you have two chains booked; run StopSchedule, then start once. If you cannot stop it, the NextRun variable is probably not module-level, so cancel by closing Excel, which clears all pending OnTime calls. If Excel becomes unresponsive at the scheduled moment, look for a dialog or a long-running loop in the worker. On Mac, some OnTime behaviour differs slightly from Windows, so verify the interval on the machine that will run it.
Frequently Asked Questions
Can the macro run when Excel is closed?
No. Application.OnTime only works while Excel is running. For scheduled tasks with Excel closed, use Windows Task Scheduler to open the workbook and run the macro on open, or move the job to a script outside Excel.
What is the shortest interval I can use?
OnTime accepts times down to one second, but very short intervals can overlap with a slow macro. Keep the interval longer than a typical run.
Does it survive closing and reopening the workbook?
No. Pending runs are cleared when Excel closes. Use Workbook_Open to call StartSchedule again, and Workbook_BeforeClose to cancel cleanly.
Why does it run at the wrong time?
Check the TimeValue string format: it is hours:minutes:seconds. A typo such as "00:5:00" is read as five hours, not five minutes.
Can I schedule several different macros?
Yes, but each needs its own stored next-run time and its own cancel routine, or they will interfere with each other.