Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Timer Loop: Step-by-Step Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

An Excel VBA timer loop repeats a block of code at a set interval, letting you refresh data, update a clock, or poll a value without freezing the workbook. The practical way to do it is with Application.OnTime, which schedules a macro to run again after a delay and returns control to Excel in between. A Do...Loop with Sleep or Wait also works, but it locks the interface until it finishes, so use it only for short, self-contained jobs.

What You'll Need

  • Excel on Windows or Mac with macros enabled (the Developer tab visible, or the ability to open the VBA editor with Alt+F11 on Windows, Option+F11 on Mac).
  • A workbook saved as .xlsm (macro-enabled) so your code survives closing and reopening.
  • A basic understanding of where to paste code: a standard module (Insert > Module) for general macros, or the ThisWorkbook module for workbook-level events.
  • For the Sleep approach only, a Windows PC. Sleep comes from a Windows API declaration and is not available on Mac Excel; use Application.Wait there instead.

Step-by-Step

  1. Open the VBA editor and add a module. Press Alt+F11 (Windows) or Option+F11 (Mac), then choose Insert > Module. A blank code window appears. Menu labels can differ slightly by Excel version and platform, but Insert > Module is consistent.

  2. Write a small macro that does the work you want repeated. Keep it short and idempotent, meaning running it twice in a row causes no harm. For example, this writes the current time into cell A1:

    Sub Tick()
        ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Now
    End Sub

    Change the sheet name and cell to match your workbook.

  3. Add the scheduling macro. This is the timer. It calls Tick once, then asks Excel to call the scheduler again after a delay. Paste this below the first macro:

    Public nextRun As Date
    
    Sub StartTimer()
        Tick
        nextRun = Now + TimeValue("00:00:05")
        Application.OnTime EarliestTime:=nextRun, _
            Procedure:="StartTimer", Schedule:=True
    End Sub

    The 00:00:05 means five seconds. Change it to whatever interval you need.

  4. Add a stop macro before you run anything. Once OnTime is scheduled, it keeps firing until you cancel it or close Excel. A stop routine is essential:

    Sub StopTimer()
        On Error Resume Next
        Application.OnTime EarliestTime:=nextRun, _
            Procedure:="StartTimer", Schedule:=False
        On Error GoTo 0
    End Sub

    The On Error Resume Next prevents an error if the timer was never started or was already stopped.

  5. Run StartTimer from the VBA editor or assign it to a button. Press F5 with the cursor inside StartTimer, or go back to Excel, right-click a shape or button, and choose Assign Macro. You should see cell A1 update every five seconds.

  6. Test the stop macro immediately. Run StopTimer and confirm A1 stops changing. If it keeps updating, the nextRun variable was reset (for example by editing code and pressing the reset button), so the stored time no longer matches the scheduled one. Closing and reopening the workbook also clears the schedule.

  7. If you prefer a blocking loop, use Application.Wait instead. This is simpler but freezes Excel until it finishes. Put a hard limit on the iterations so it cannot run forever:

    Sub BlockingLoop()
        Dim i As Long
        For i = 1 To 10
            ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Now
            Application.Wait Now + TimeValue("00:00:05")
            DoEvents
        Next i
    End Sub

    DoEvents lets Excel process queued clicks and redraws between waits, but the interface still feels sluggish. Use this only for short jobs.

  8. For a true clock-style display, format the cell. Select A1, press Ctrl+1 (Cmd+1 on Mac), choose Custom, and enter hh:mm:ss. The value stays a real date-time, so other formulas can still compare it.

  9. Save the workbook as .xlsm. Use File > Save As and pick Excel Macro-Enabled Workbook. A plain .xlsx save strips the macros and the timer will not exist next time.

Common Mistakes

  • Scheduling without storing the exact time. OnTime cancels only if you pass the same EarliestTime value used to schedule. Recomputing Now + TimeValue(...) at stop time will not match, so keep it in a module-level variable as shown.
  • Running StartTimer twice. Each run schedules another chain, so the macro fires twice as often. Stop first, then start, or check a flag before scheduling.
  • Using a plain Do...Loop with no exit. An infinite loop with no stop condition locks Excel and can only be interrupted with Esc or Ctrl+Break (Windows) or Cmd+Period (Mac), and sometimes not at all. Always cap the iterations.
  • Expecting the timer to survive closing the workbook. OnTime schedules live in the running Excel instance. Close Excel and the schedule is gone; reopen and run StartTimer again.
  • Forgetting that Sleep is Windows-only. Pasting a Windows API declaration into Mac Excel produces a compile error. Use Application.Wait for cross-platform code.

Tips

  • Keep the interval at one second or longer. Very short intervals make Excel unresponsive and can queue up overlapping calls.
  • Wrap the body of your repeated macro in error handling so one failure does not break the chain. If Tick errors, the scheduler still runs, but you may want to log the error to a cell or text file.
  • Use ThisWorkbook.Worksheets("Sheet1") rather than ActiveSheet, because the active sheet can change between timer runs.
  • If you need the timer to stop when the workbook closes, add StopTimer to the Workbook_BeforeClose event in the ThisWorkbook module.
  • For anything that must run while Excel is closed, a VBA timer cannot help; use Windows Task Scheduler to open the workbook and run a macro, or move the job to Power Automate.

Troubleshooting

The macro never fires. Check that macros are enabled (File > Options > Trust Center > Trust Center Settings > Macro Settings) and that the workbook is saved as .xlsm. Confirm the procedure name in OnTime matches the macro exactly, including case-insensitive spelling and no module prefix.

It fires twice as fast as expected. You have two scheduled chains. Run StopTimer, then close and reopen the workbook to clear any orphaned schedule, and start once.

StopTimer raises an error. The schedule was already cancelled or never created. The On Error Resume Next line handles this; if you removed it, put it back.

Excel becomes unresponsive. Your interval is too short or the repeated macro does too much work. Increase the interval, or move heavy calculations outside the timer and run them on demand.

It worked, then stopped after you edited the code. Pressing the Reset button in the VBA editor clears all variables, including nextRun, so the stop macro can no longer match the scheduled time. Close and reopen the workbook, then restart the timer.

Frequently Asked Questions

Can a VBA timer run while Excel is closed?

No. Application.OnTime only works inside a running Excel instance. For scheduled jobs with Excel closed, use Windows Task Scheduler to launch the workbook, or use Power Automate.

What is the shortest reliable interval for OnTime?

Excel stores times to the second, so one second is the practical minimum. Anything shorter is rounded, and the macro may run back-to-back and make the interface sluggish.

Does Application.Wait freeze Excel?

Yes. Wait pauses the macro and Excel does not respond to input until the wait ends. DoEvents inside the loop helps redraw the screen but does not make the workbook fully usable.

Why does my timer stop when I close and reopen the file?

The schedule is not saved in the workbook. Reopen the file and run your start macro again, or call it from the Workbook_Open event.

Can I run two timers at different intervals?

Yes. Use separate scheduling macros and separate module-level variables to store each EarliestTime, so each can be cancelled independently.

Is Sleep faster than Application.Wait?

Sleep can pause for milliseconds and is Windows-only; Wait works on both Windows and Mac but has one-second resolution. For most workbook tasks the difference does not matter.