Excel Timers
Post date: Sep 8, 2020 5:44:28 PM
Need things to repeat on a timer?
This shows two methods for creating timers in Excel which we can use for countdowns, uptime counters, dashboard updates, etc. The first method uses VBA and is to-the-second accurate. The second method uses PowerQuery. It is accurate only to the minute but doesn't require VBA which can cause security concerns and trust alerts. Both methods allow Excel to respond to events and run other VBA routines while the timer is running.
VBA
This method can use one second intervals. It leverages Excel's OnTime function to wait for a set period of time without holding up our VBA. It has three routines stored in a regular module: SetInterval, Schedule, and Unschedule.
SetInterval("00:00:02")
Call Schedule() to start the timer. Embed calls to routines we want to execute at this interval in this subroutine.
Call Unschedule() to stop the timer
Option Explicit
Dim dNextEvent As Date
Dim dInterval As Date
Public Sub SetInterval(ByVal vInterval As Variant)
dInterval = CDate(vInterval)
End Sub
Public Sub Schedule()
'Example of how to display results: [A1].Value = Now
dNextEvent = Now + dInterval
Application.OnTime EarliestTime:=dNextEvent, _
Procedure:="Schedule", _
Schedule:=True
End Sub
Public Sub Unschedule()
Application.OnTime EarliestTime:=dNextEvent, _
Procedure:="Schedule", _
Schedule:=False
End Sub
Power Query
This method creates a table with the current timestamp. When the table changes it generates a worksheet change event which we can leverage to trigger other actions such as sending out emails or refreshing PivotTables.
Steps
In Excel use menu option: Data > New Query > From other sources > Blank Query
In PQ use menu option Advanced Editor and make this edit
let
Source = DateTime.LocalNow
in
Source
Click Done
Click Invoke
Click File > Close & Load
In Excel click Table Tools Design > Properties
Click small icon (connection properties) next to Name:
Check Refresh Every and set to however many minutes you want
Click OK twice to close properties dialog
Summary
Both methods allow us to continue working with Excel normally. US the VBA method if you are comfortable with VBA and can deal with Excel's trust warnings. Use the PQ method if you don't need the timer to be to-the-second accurate and would like to avoid VBA concerns.
Call SetInterval() to set how long to wait between events. It can be called like this for a two second interval: