The OnTime method in Excel’s Application object is a powerful feature for scheduling the execution of a procedure at a specific future time or after a specific time interval. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model. This allows for the automation of repetitive tasks, data refreshes, or timed notifications without user intervention, effectively enabling time-driven macros within a Python-controlled Excel environment.
Functionality:
The primary function is to run a specified VBA macro (procedure) at a predetermined time. It can be used for one-time execution or to set up recurring schedules. While xlwings itself runs Python code, OnTime schedules the execution of VBA macros stored in the Excel workbook. Therefore, typical use involves writing a VBA macro that, when triggered, can call back into Python via xlwings’ RunPython function or perform native Excel operations. This creates a hybrid automation model.
Syntax in xlwings:
The call is made through the Excel Application object. The syntax in xlwings is:
app.api.OnTime(EarliestTime, Procedure, LatestTime, Schedule)
- EarliestTime (Required): The time when the procedure should be run. It is a serial Excel date/time value. In practice, it’s often created using
datetimeortimemodules. Example:datetime.datetime.now() + datetime.timedelta(seconds=10). - Procedure (Required): A string specifying the name of the VBA macro to run. This macro must be present in a standard VBA module in the workbook (e.g., “Module1.MyMacro”).
- LatestTime (Optional): The latest time for the procedure to run. If Excel is not in Ready, Copy, Cut, or Find mode at
EarliestTime, it will wait until it enters one of these states, but only untilLatestTime. If omitted, Excel waits indefinitely. - Schedule (Optional): A boolean value.
Trueto schedule a newOnTimeprocedure (default).Falseto clear a previously set procedure that has not yet run.
Code Example:
This example schedules a VBA macro named “RefreshData” to run 5 seconds from now. The VBA macro itself could contain code to call a Python function or refresh queries.
import xlwings as xw
import datetime
# Connect to the active Excel instance or create a new one
app = xw.apps.active
# Calculate the time for execution (5 seconds from now)
run_time = datetime.datetime.now() + datetime.timedelta(seconds=5)
# Schedule the OnTime call. The macro "RefreshData" must exist in the workbook.
app.api.OnTime(EarliestTime=run_time, Procedure="RefreshData")
print(f"Scheduled 'RefreshData' to run at approximately {run_time}")
To cancel a scheduled procedure before it executes, you would call OnTime with the same EarliestTime and Procedure, but set Schedule to False:
# Cancel the previously scheduled "RefreshData" macro
app.api.OnTime(EarliestTime=run_time, Procedure="RefreshData", Schedule=False)
Leave a Reply