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

runtime.startup

Once when xlwings Lite starts, see Startup.

None

Workbook

Event

Runs

Options

book.activated

When the workbook is activated, e.g. when you switch back to its window. Not when it’s opened: use runtime.startup for that.

debounce

book.selection_changed

When the selection changes on any sheet.

debounce

Sheets

Event

Runs

Options

sheet.activated

When a sheet is activated.

sheet, debounce

sheet.deactivated

When a sheet is deactivated, e.g. because you switch to another sheet.

sheet, debounce

sheet.added

When a sheet is added.

sheet, debounce, include_remote

sheet.deleted

When a sheet is deleted.

sheet, debounce, include_remote

sheet.name_changed

When a sheet is renamed.

sheet, debounce, include_remote

sheet.visibility_changed

When a sheet is hidden or unhidden.

sheet, debounce, include_remote

sheet.moved

When a sheet is moved to another position.

sheet, debounce, include_remote

sheet.protection_changed

When a sheet is protected or unprotected.

sheet, debounce, include_remote

Cells

Event

Runs

Options

sheet.changed

When cells change, see Cell changes.

sheet, range, debounce, include_remote, include_own_changes

sheet.calculated

When a sheet has been recalculated.

sheet, debounce

sheet.selection_changed

When the selection changes on a sheet.

sheet, range, debounce

sheet.single_clicked

When you click a cell with the left mouse button.

sheet, range, debounce

sheet.format_changed

When the format of cells changes, e.g. the fill color or font.

sheet, range, debounce, include_remote

sheet.formula_changed

When a formula changes. Only for cells that already had a formula.

sheet, range, debounce, include_remote

sheet.row_sorted

When rows are sorted.

sheet, debounce, include_remote

sheet.column_sorted

When columns are sorted, i.e. sorted left to right.

sheet, debounce, include_remote

sheet.row_hidden_changed

When rows are hidden or unhidden. Not for advanced filters.

sheet, debounce, include_remote

Tables

Event

Runs

Options

table.added

When a table is added.

sheet, table, debounce, include_remote

table.deleted

When a table is deleted.

sheet, table, debounce, include_remote

table.changed

When cells of a table change.

sheet, table, debounce, include_remote

table.selection_changed

When the selection changes and overlaps a table. Requires table.

table, sheet, debounce

Charts

Event

Runs

Options

chart.activated

When a chart is activated, e.g. by clicking it, or added.

sheet, chart, debounce

chart.deactivated

When a chart is deactivated, e.g. by clicking a cell.

sheet, chart, debounce

chart.added

When a chart is added.

sheet, chart, debounce, include_remote

chart.deleted

When a chart is deleted.

sheet, chart, debounce, include_remote

Comments

Event

Runs

Options

comment.added

When a comment is added.

sheet, range, debounce, include_remote

comment.changed

When a comment is edited, resolved, or reopened, or when a reply is added, edited, or deleted.

sheet, range, debounce, include_remote

comment.deleted

When a comment is deleted.

sheet, debounce, include_remote

Shapes

Event

Runs

Options

shape.activated

When a shape is activated, e.g. by clicking it. Requires sheet and shape.

sheet, shape, debounce

shape.deactivated

When a shape is deactivated. Requires sheet and shape.

sheet, shape, debounce

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.txt pins 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.Book or xw.BookAsync type hint. It receives the workbook, as with scripts.

  • can have one parameter with an xw.Event type 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, use xw.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

name

The event, e.g. "sheet.changed".

sheet

The name of the sheet, e.g. "Inputs".

table, chart, shape

For table, chart, and shape events, the name of the table, chart, or shape, e.g. "Sales".

address

The cells of the event without the sheet name, e.g. "B2:C3". For combined events, the addresses separated by commas.

change_type

For sheet.changed and table.changed, the kind of change: "range_edited", "row_inserted", "row_deleted", "column_inserted", "column_deleted", "cell_inserted", "cell_deleted", or "unknown". For sheet.row_hidden_changed, "hidden" or "unhidden". For comment.changed, "comment_edited", "comment_resolved", "comment_reopened", "reply_added", "reply_edited", or "reply_deleted".

before, after

The value before and after the change:

  • sheet.changed and table.changed: the cell values, if a single cell changed. An empty cell is None. For combined changes of the same cell, the value before the first and after the last change. These are the raw cell values without xlwings’ conversion: dates are Excel serial numbers (e.g. 46000.0) and errors are strings (e.g. "#DIV/0!").

  • sheet.name_changed: the old and new name.

  • sheet.visibility_changed: "visible", "hidden", or "very_hidden".

  • sheet.moved: the old and new position of the sheet, starting at 0.

source

"local" for your own changes, "remote" for a coauthor’s changes. None for events that don’t report it, e.g. selection changes.

count

The number of events that were combined into this run, usually 1.

stale

True if the handler had to wait more than 30 seconds, e.g. for a long Wingman request.

raw

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_changed works like sheet.selection_changed for every sheet: event.sheet and event.address tell you where the selection is.

  • sheet.calculated: event.address holds the recalculated cells. With older versions of Excel, it’s None.

  • sheet.deleted: event.sheet is the name the sheet had.

  • sheet.formula_changed: event.address holds the cells whose formula changed and event.raw["formulaDetails"] their previous formulas. If many formulas change at once, Excel doesn’t report the cells, and event.address is None.

  • sheet.row_sorted and sheet.column_sorted: event.address holds the cells that moved, not the whole sorted range.

  • sheet.protection_changed: event.raw["isProtected"] says whether the sheet is now protected.

  • table.selection_changed runs when the new selection overlaps the table given by table, not when the selection leaves it.

  • chart.deleted: event.chart is 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.added and comment.changed: event.address holds the cells of the comments. For comment.deleted, the comment is gone, so event.address is None and the range option isn’t available. The comment IDs are in event.raw["commentDetails"].

  • shape.activated and shape.deactivated only 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 the shape option.

  • 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.address also 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 debounce and xw.BookAsync for 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

sheet="Inputs"

Only run for events on this sheet. The name isn’t case-sensitive. If you rename the sheet, update the option too.

range="B2:B20"

Only run if the event’s cells overlap this range. Requires sheet. Accepts addresses such as "B2", "B2:D10", "B:B" (whole columns), "2:5" (whole rows), or several of them separated by commas, e.g., "B2:B20,D2". Instead of an address, you can use a defined name, e.g., range="Prices". It’s looked up when an event occurs, so it follows inserted rows and changes in the Name Manager. A name that belongs to the sheet takes precedence over a workbook name of the same name. If the name doesn’t exist or refers to cells on another sheet, the handler doesn’t run and the Output pane says so.

table="Sales"

Only run for events of this table. The name isn’t case-sensitive. If you rename the table, update the option too.

chart="Revenue"

Only run for events of this chart. The name isn’t case-sensitive. If you rename the chart, update the option too.

shape="Rectangle 1"

The shape whose events run the handler, on the sheet given by sheet. Required for shape events. The name isn’t case-sensitive.

debounce=500

Wait until there were no events for this many milliseconds before running, see When handlers run. Defaults to 0.

include_own_changes=True

Only for sheet.changed: also run for changes that xlwings Lite made itself, see Loop protection. Defaults to False.

include_remote=True

Also run for changes that coauthors made in a shared workbook. Defaults to False, as otherwise the handler would run in every coauthor’s xlwings Lite and write the same results several times. Only available for events that report who made the change, see the table at the top.

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.calculated handler 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_changed only counts format changes. Writing values or formulas doesn’t count, even if Excel formats them automatically, e.g. as a date.

  • sheet.single_clicked and book.activated can 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.py or another source file. A handler that is only imported into another file, such as from utils import initialize in main.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_remote keeps 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 a sheet.calculated handler 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.