Event handlers
An event handler is a Python function that xlwings Lite runs automatically when an event occurs, without clicking a button. You declare it with the @xw.on decorator.
Events
xlwings Lite supports the following events:
Startup
Event |
Runs |
Options |
|---|---|---|
|
Once when xlwings Lite starts, see Startup. |
None |
Workbook
Event |
Runs |
Options |
|---|---|---|
|
When the workbook is activated, e.g. when you switch back to its window. Not when it’s opened: use |
|
|
When the selection changes on any sheet. |
|
Sheets
Event |
Runs |
Options |
|---|---|---|
|
When a sheet is activated. |
|
|
When a sheet is deactivated, e.g. because you switch to another sheet. |
|
|
When a sheet is added. |
|
|
When a sheet is deleted. |
|
|
When a sheet is renamed. |
|
|
When a sheet is hidden or unhidden. |
|
|
When a sheet is moved to another position. |
|
|
When a sheet is protected or unprotected. |
|
Cells
Event |
Runs |
Options |
|---|---|---|
|
When cells change, see Cell changes. |
|
|
When a sheet has been recalculated. |
|
|
When the selection changes on a sheet. |
|
|
When you click a cell with the left mouse button. |
|
|
When the format of cells changes, e.g. the fill color or font. |
|
|
When a formula changes. Only for cells that already had a formula. |
|
|
When rows are sorted. |
|
|
When columns are sorted, i.e. sorted left to right. |
|
|
When rows are hidden or unhidden. Not for advanced filters. |
|
Tables
Event |
Runs |
Options |
|---|---|---|
|
When a table is added. |
|
|
When a table is deleted. |
|
|
When cells of a table change. |
|
|
When the selection changes and overlaps a table. Requires |
|
Charts
Event |
Runs |
Options |
|---|---|---|
|
When a chart is activated, e.g. by clicking it, or added. |
|
|
When a chart is deactivated, e.g. by clicking a cell. |
|
|
When a chart is added. |
|
|
When a chart is deleted. |
|
Comments
Event |
Runs |
Options |
|---|---|---|
|
When a comment is added. |
|
|
When a comment is edited, resolved, or reopened, or when a reply is added, edited, or deleted. |
|
|
When a comment is deleted. |
|
Shapes
Event |
Runs |
Options |
|---|---|---|
|
When a shape is activated, e.g. by clicking it. Requires |
|
|
When a shape is deactivated. Requires |
|
Instead of the event name, you can use its constant, which is the name in uppercase with an underscore instead of the dot, e.g. xw.events.SHEET_CHANGED for "sheet.changed". The options are described in Options.
Note
Event handlers require xlwings>=0.37.15. If
requirements.txtpins an older version, the Problems tab shows the import error together with a hint to update it.Some events require a recent version of Excel. Excel for Microsoft 365 and Excel on the web support all of them. If your Excel version doesn’t support an event, the Problems tab shows an error with the required version, and the handler doesn’t run for this event.
Examples
Startup
A runtime.startup handler prepares the workbook, e.g., refreshes data from a web API or resets input cells to their defaults:
import datetime as dt
import xlwings as xw
@xw.on("runtime.startup")
def initialize(book: xw.Book):
book.sheets["Dashboard"]["B1"].value = dt.datetime.now()
It runs each time xlwings Lite starts: once the workbook code is trusted and imported without error, and before custom functions, sheet buttons, and App Mode are available. It also runs after xlwings Lite menu (☰) > Restart, so make it safe to run several times, e.g., overwrite a cell instead of appending a row. With the Startup Behavior Do not autostart, it only runs once you open xlwings Lite. A workbook can have at most one startup handler.
Cell changes
A handler for sheet.changed runs when cells on a worksheet change, for example, when you enter a value, paste, clear cells, or insert or delete rows:
import xlwings as xw
@xw.on("sheet.changed", sheet="Inputs", range="B2:B20")
async def inputs_changed(book: xw.BookAsync, event: xw.Event):
sheet = book.sheets["Inputs"]
sheet["D2"].value = f"Last change: {event.address}"
Without options, the handler runs for changes on any sheet. A function can have several @xw.on decorators, e.g., to watch two ranges or to react to several events. If an event matches more than one of them, e.g., because the ranges overlap, the handler still runs only once.
Selection
All events work the same way: only the event name and the options differ. For example, to highlight the row of the selected cell in a table:
@xw.on("sheet.selection_changed", sheet="Orders", range="A2:F500")
async def highlight_row(book: xw.BookAsync, event: xw.Event):
sheet = book.sheets["Orders"]
sheet["A2:F500"].color = None
row = sheet[event.address.split(",")[0]].row
sheet[f"A{row}:F{row}"].color = "#FFF2CC"
Function signature
An event handler:
needs exactly one parameter with an
xw.Bookorxw.BookAsynctype hint. It receives the workbook, as with scripts.can have one parameter with an
xw.Eventtype hint, which receives the event that triggered the handler, see The event argument.can’t have other parameters, except if they have a default value.
can be a regular function (
def) or a coroutine function (async def). For the latter, usexw.BookAsync, see Async API.
Whatever the handler returns is ignored.
The event argument
To learn about the event that triggered the handler, add a parameter with the xw.Event type hint:
@xw.on("sheet.changed", sheet="Inputs")
def inputs_changed(book: xw.Book, event: xw.Event):
print(event.name, event.sheet, event.address) # sheet.changed Inputs B2
xw.Event has the following attributes. Attributes that don’t apply to an event are None.
Attribute |
Description |
|---|---|
|
The event, e.g. |
|
The name of the sheet, e.g. |
|
For table, chart, and shape events, the name of the table, chart, or shape, e.g. |
|
The cells of the event without the sheet name, e.g. |
|
For |
|
The value before and after the change:
|
|
|
|
The number of events that were combined into this run, usually |
|
|
|
The event as Excel reported it, for details that aren’t covered by the other attributes. |
Event details
Some events have details that are worth knowing:
book.selection_changedworks likesheet.selection_changedfor every sheet:event.sheetandevent.addresstell you where the selection is.sheet.calculated:event.addressholds the recalculated cells. With older versions of Excel, it’sNone.sheet.deleted:event.sheetis the name the sheet had.sheet.formula_changed:event.addressholds the cells whose formula changed andevent.raw["formulaDetails"]their previous formulas. If many formulas change at once, Excel doesn’t report the cells, andevent.addressisNone.sheet.row_sortedandsheet.column_sorted:event.addressholds the cells that moved, not the whole sorted range.sheet.protection_changed:event.raw["isProtected"]says whether the sheet is now protected.table.selection_changedruns when the new selection overlaps the table given bytable, not when the selection leaves it.chart.deleted:event.chartis the name the chart had when xlwings Lite last saw it: when you saved the code or when the chart was added. If the chart was renamed since, it’s the old name.comment.addedandcomment.changed:event.addressholds the cells of the comments. Forcomment.deleted, the comment is gone, soevent.addressisNoneand therangeoption isn’t available. The comment IDs are inevent.raw["commentDetails"].shape.activatedandshape.deactivatedonly work for shapes that exist when you save the code, as Excel has no event for added shapes: if you add the shape later, save the code again. If the shape doesn’t exist, the Output tab says so. If you rename the shape, update theshapeoption.Selection events report the whole selection, which can be whole rows or columns, e.g.
"5:5"or"B:B", or several areas. If events were combined while the handler waited,event.addressalso lists the earlier selections, in the order they happened. To act on the current selection, read it when the handler runs, e.g.cell = (await book.get_selection())[0, 0]for its top-left cell.Selection changes and recalculations can be very frequent. Use
debounceandxw.BookAsyncfor them, see When handlers run.
Options
Options filter the events that run a handler. The table at the top lists which options each event accepts.
Option |
Description |
|---|---|
|
Only run for events on this sheet. The name isn’t case-sensitive. If you rename the sheet, update the option too. |
|
Only run if the event’s cells overlap this range. Requires |
|
Only run for events of this table. The name isn’t case-sensitive. If you rename the table, update the option too. |
|
Only run for events of this chart. The name isn’t case-sensitive. If you rename the chart, update the option too. |
|
The shape whose events run the handler, on the sheet given by |
|
Wait until there were no events for this many milliseconds before running, see When handlers run. Defaults to |
|
Only for |
|
Also run for changes that coauthors made in a shared workbook. Defaults to |
The Problems tab marks unknown options, options with an invalid value, and options that don’t apply to the event. The handler then doesn’t run for this decorator.
When handlers run
Handlers run one at a time and never at the same time as a script, a test, or a Wingman request. If an event occurs while something else runs, the handler runs afterwards. During a Wingman request, it runs after Wingman has finished.
While a handler waits, further events for it aren’t queued one by one but combined into a single run: event.address then lists all addresses separated by commas, e.g. "B2,B5:B6", and event.count says how many events were combined. Events on different sheets, tables, charts, or shapes run separately. With debounce, the handler also waits until the events have stopped for the given time, which is useful if you type into several cells in a row.
While a handler runs, the Run button is busy, so you can’t start a script at the same time.
A handler with an xw.Book parameter reads the values of all sheets before it runs, as a script does. As events can be frequent, prefer xw.BookAsync, which only reads what you access, see Async API.
Loop protection
A handler that writes to the workbook can trigger its own event again. For example, a sheet.calculated handler that writes values causes another recalculation, which runs the handler again, and so on. xlwings Lite prevents such loops automatically: a handler doesn’t run for the events that its own changes cause. How xlwings Lite recognizes these events depends on the event.
Changes to cells: for sheet.changed, Excel reports whether a change came from xlwings Lite. So by default, a sheet.changed handler doesn’t run for any change made by xlwings Lite: not for its own, and not for changes made by scripts, other handlers, or Wingman.
To also run for these changes, use include_own_changes=True. Then make sure the handler doesn’t write to the range it watches, or it triggers itself.
All other events: Excel doesn’t report who caused them, so xlwings Lite goes by timing instead: after a handler has written to the workbook, it ignores its events while it runs and for one second after it has finished. That’s when Excel reports the events caused by the handler’s changes.
Only the handler that wrote ignores events. Other handlers still run.
A handler that only reads from the workbook never ignores events.
The downside: an event that you cause during this time is ignored too. For example, if you edit a cell within a second after a
sheet.calculatedhandler has written values, the handler doesn’t run for your edit.
Writes that can’t cause an event don’t count:
Selection and activation events only count writes that can select or activate something, e.g. selecting a range, adding or activating a sheet, or changes via Office.js. Writing values or formats doesn’t count, so a handler that colors the selected cell runs for every click.
sheet.format_changedonly counts format changes. Writing values or formulas doesn’t count, even if Excel formats them automatically, e.g. as a date.sheet.single_clickedandbook.activatedcan only be caused by you, so they’re never ignored.
Loops between handlers: if changes that xlwings Lite may have made itself trigger the same handler more than five times in a row, e.g. because two handlers keep triggering each other, xlwings Lite assumes a loop and pauses the handler, see Errors.
Running a handler manually
An event handler isn’t a script: it doesn’t show up in the scripts dropdown, App Mode, or as a sheet button. To also run it manually, add the @script decorator. The order of the two decorators doesn’t matter:
@xw.script(name="Refresh Dashboard")
@xw.on("runtime.startup")
def refresh(book: xw.Book, event: xw.Event | None = None):
book.sheets["Dashboard"]["B1"].value = dt.datetime.now()
When you run the script manually, there’s no event, so event is None. A script therefore has to annotate its event parameter as xw.Event | None, e.g., event: xw.Event | None = None. With a plain xw.Event annotation, the decorator raises an error that shows up in the Problems tab.
The script configuration (e.g., include and exclude) also applies when the handler runs automatically.
To test a handler with pytest, call it with an xw.Event that you create yourself, see Testing scripts and event handlers.
Errors
If a handler raises an exception, the Output tab shows the traceback followed by e.g. Event handler main:initialize failed (runtime.startup)., where main:initialize stands for the function initialize in main.py. xlwings Lite doesn’t switch to the Output tab, but if the task pane is hidden, e.g. with Autostart in the background, it opens so you see the error.
If the startup handler fails, custom functions and sheet buttons are registered anyway, but the other event handlers stay inactive until the next start, as they may rely on the startup handler.
If an event handler fails three times in a row, xlwings Lite pauses it, so a broken handler doesn’t produce an error with every event. The same happens if it appears to run in a loop (see Loop protection). The Output and Problems tabs show that the handler was paused. Once you save a change to the code, or restart xlwings Lite, it runs again.
Changes that the handler made before the exception aren’t rolled back. This includes everything that it wrote with book.flush() or via Office.js.
If a workbook file can’t be imported, e.g., because of a syntax error, the startup handler doesn’t run, and the Problems tab shows the import error.
If a workbook has several startup handlers, none of them runs, and the Problems tab marks each of them.
The Problems tab also shows handlers that can’t run, for example because of a wrong signature or an unknown event name.
Limitations
Source files: Event handlers have to be defined in the workbook’s source files, i.e., in
main.pyor another source file. A handler that is only imported into another file, such asfrom utils import initializeinmain.py, counts once, in the file that defines it.Personal modules and plugins: Personal modules and plugins can’t declare event handlers. If they do, the handler is ignored and the Problems tab shows a warning.
Shared workbooks: In a workbook that several people edit at the same time, each of them runs the event handlers in their own xlwings Lite.
include_remotekeeps a handler from reacting to the others’ changes, but only for events that report who made a change. Other events can also be caused by a coauthor: e.g., a coauthor’s edit recalculates the workbook for everyone, so asheet.calculatedhandler runs in every coauthor’s xlwings Lite. Write such handlers so they can run several times without harm, e.g., overwrite cells instead of appending rows.