Excel VBA Timer: Measure Code and Schedule Macros Safely

VBA & macros · Updated November 8, 2026

In Excel VBA, use the Timer function to measure elapsed time, and use Application.OnTime to schedule a macro to run later. They solve different problems: Timer returns seconds since midnight, while OnTime asks Excel to run a procedure at a specified clock time.

What “timer” means in Excel VBA

There is no single VBA timer object that automatically repeats a macro. People searching for an “Excel VBA timer” usually mean one of three things: measuring how long code takes, delaying a macro, or running a procedure repeatedly at intervals. The right approach depends on which task you mean.

  • Measure duration: record the value of Timer before and after the work.
  • Run once later: schedule a procedure with Application.OnTime.
  • Repeat periodically: have the scheduled procedure schedule its next run, and provide a way to cancel it.

Neither method is a real-time clock for controlling Excel at subsecond precision. Excel must be available to process a scheduled callback, and workbook calculations, dialogs, or other running code can delay it.

Measure elapsed time with Timer

The VBA Timer function returns a Single value representing the number of seconds elapsed since midnight. The value can include a fractional part, so subtracting a starting value from an ending value gives a useful elapsed-time estimate for ordinary macro benchmarks. The following example prints the result in Excel’s Immediate window in the Visual Basic Editor.

In the Visual Basic Editor, insert this in a standard module. On Windows, open the editor with Alt+F11; on Mac, use Option+F11 (some keyboards require Fn as well), or open the editor from Excel’s Developer tools.

Option Explicit

Public Sub MeasureLoop()
    Dim startedAt As Single
    Dim elapsedSeconds As Double
    Dim i As Long

    ' Save a copy of the workbook before running a macro.
    startedAt = Timer

    For i = 1 To 1000000
        ' Example workload; replace with the code to measure.
    Next i

    elapsedSeconds = Timer - startedAt

    ' Timer starts over at midnight, so correct a crossing.
    If elapsedSeconds < 0 Then elapsedSeconds = elapsedSeconds + 86400#

    Debug.Print Format$(elapsedSeconds, "0.000") & " seconds"
End Sub

Run the procedure with F5 while the cursor is inside it, then view the Immediate window in the editor (Ctrl+G on Windows). On Mac, use the corresponding Command-key shortcut if configured, or select the Immediate window from the View menu. The example’s loop is just a placeholder: replace it with the operation you want to time. It does not have a fixed expected duration because speed depends on the computer, Excel version, workbook, and other activity.

The midnight correction adds 86,400 seconds—the number of seconds in a day—if the end reading is lower than the start reading. It is suitable when the measured operation takes less than a day. For longer-running work, or code that needs robust timestamps across dates, record Now at the start and end and subtract the dates instead. Keep in mind that Now is a date-and-time value, not a high-resolution performance counter.

Benchmark code fairly

A timer result is useful only if the measured work is consistent. When comparing two approaches, run each against the same data and conditions, and repeat the measurement. Excel may be doing other work, such as recalculating formulas or updating the screen, so a single result can be misleading.

  • Measure the specific operation, not unrelated setup or user prompts.
  • Use the same workbook state and input range for each comparison.
  • Repeat the test and compare typical results rather than relying on one run.
  • For very short procedures, time a repeated batch of operations; the timing overhead and system scheduling can otherwise be a large part of the measurement.
  • Use Debug.Print or a log cell to report results, rather than displaying a message box inside the timed section.

For example, if a macro transforms 50,000 rows, time the transformation with the same rows and settings before and after a code change. Do not conclude that one version is faster just because it happened to run while Excel was idle and the other ran during recalculation. If the macro changes workbook contents, use a disposable copy or restore the same starting state between runs.

Schedule a macro with Application.OnTime

Application.OnTime schedules a procedure for a particular date and time. It is useful for a reminder, a one-time delayed action, or a modest repeating task. A repeating timer is implemented by scheduling another callback after each run, rather than by asking VBA to hold a thread open.

This example updates cell A1 on a worksheet named Sheet1 about once per second while the ticker is running. Put all of it in a standard module, and change the worksheet reference if needed. Save a copy of the workbook before running it; VBA changes cannot be undone with Ctrl+Z on Windows or Command+Z on Mac.

Option Explicit

Private nextRun As Date
Private timerRunning As Boolean

Public Sub StartTicker()
    If timerRunning Then Exit Sub
    timerRunning = True
    ScheduleNextTick
End Sub

Private Sub ScheduleNextTick()
    ' Schedule the next callback about one second from now.
    nextRun = Now + TimeSerial(0, 0, 1)
    Application.OnTime EarliestTime:=nextRun, Procedure:="Tick", Schedule:=True
End Sub

Public Sub Tick()
    If Not timerRunning Then Exit Sub

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

Public Sub StopTicker()
    timerRunning = False

    ' Cancel the same time and procedure that were scheduled.
    On Error Resume Next
    Application.OnTime EarliestTime:=nextRun, Procedure:="Tick", Schedule:=False
    On Error GoTo 0
End Sub

Run StartTicker to begin and StopTicker to cancel. The callback procedure must be available to Excel—using a public procedure in a standard module is the usual arrangement—and it should not require arguments. The sample assumes the named worksheet exists. If it does not, the callback will raise an error, so adapt the reference before starting the schedule.

Cancel scheduled callbacks and handle closing

Cancellation requires the scheduled time and procedure name to match the original call. That is why the example stores its next scheduled date in the module-level variable nextRun. If code calculates a new time instead of using the saved value, the cancellation may fail to identify the pending callback. The procedure name also matters; if the macro name or workbook qualification changes, use the same procedure string for scheduling and cancellation.

A repeating callback can remain pending when a user closes a workbook. For a workbook that uses this pattern, call StopTicker from the Workbook_BeforeClose event in the ThisWorkbook code module. The event procedure belongs in that module, not in the standard module:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ' Cancel the pending OnTime callback before closing.
    StopTicker
End Sub

Test the close behavior in a copy of the workbook. If Excel cannot find the callback when the scheduled time arrives, or if a callback tries to use a workbook that is no longer available, the result can be an error or a confusing delay. A close event that cancels the pending run reduces that risk.

Accuracy, delays, and common problems

Application.OnTime is intended for scheduling Excel procedures, not precise real-time control. Excel may not run the callback at the exact requested instant if it is busy, a dialog is open, or another macro is still running. Treat “one second” in the example as an approximate interval, not a guaranteed cadence. Repeated callbacks can drift because each next run is scheduled after the current callback executes.

  • The macro does not run: confirm macros are enabled, the procedure is public and in a standard module, and the scheduled time has not already passed.
  • It runs more than once: prevent duplicate starts, as StartTicker does, and cancel the pending callback before restarting.
  • Stop does not work: check that the saved time and procedure string exactly match the scheduled call.
  • The callback is late: Excel may be occupied; OnTime does not interrupt a running procedure or bypass a modal dialog.
  • The cell reference fails: check that the worksheet name in the code matches the tab name exactly.

Keep callback work short. A callback that takes longer than its intended interval can make scheduling behavior harder to reason about, and heavy recalculation or screen updates may make the workbook feel unresponsive. Do not use a loop with DoEvents as a substitute for a scheduled callback unless you specifically need a loop and understand how it affects responsiveness; it can also allow other events to run while your code is partway through its work.

Choosing between Timer, OnTime, and other methods

Choose based on the job, not on the word “timer.” Use Timer for elapsed-time measurement within a macro. Use Application.OnTime when Excel should run a procedure later or periodically while Excel remains available. Neither is a dependable choice for hard deadlines, background service work, or precise subsecond scheduling.

For an elapsed duration that must span midnight or last a long time, date subtraction with Now is simpler to reason about than relying on the seconds-since-midnight value alone. For detailed performance profiling, the Visual Basic Editor’s debugging tools and carefully designed repeated tests can help isolate slow sections. Windows has operating-system timing APIs, but those require platform-specific declarations and careful compatibility work; they are not a drop-in replacement for the simple VBA function and should only be used when the additional precision is genuinely needed.

Excel for the web cannot run VBA macros. VBA editing and running are desktop Excel capabilities; Mac desktop Excel supports VBA, but Windows-specific API code is not automatically portable to Mac. The examples here use built-in VBA and Excel scheduling rather than Windows API calls.

Frequently Asked Questions

What does Timer return in VBA?
Timer returns a Single value for the seconds elapsed since midnight, including a fractional part. Because it starts over at midnight, subtracting readings needs a rollover correction if the measured code crosses midnight.

How do I run a VBA macro every second?
Use Application.OnTime to schedule a public procedure, then have that procedure schedule its next run. Provide a cancellation macro and cancel pending work before the workbook closes. The interval is approximate, not a precise one-second guarantee.

Can Application.OnTime run a macro when Excel is closed?
No. It schedules work for the Excel application; it is not a background service that launches Excel or runs after Excel has closed. Keep Excel available and cancel pending callbacks before closing the workbook.

Why does my VBA timer reset to zero?
The built-in Timer function counts seconds from midnight, so its value starts over at midnight. Add 86,400 seconds to a negative elapsed result for a short measurement crossing midnight, or use date-and-time subtraction for longer periods.

Can I use a VBA timer in Excel for the web?
No. Excel for the web does not execute VBA macros. Open the workbook in desktop Excel to run VBA; if it must work in a browser, consider an alternative such as Office Scripts, which is a different automation system and does not use VBA’s Timer or Application.OnTime.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.