Custom Scripts

Custom Scripts or just “scripts” are the equivalent to a Sub in VBA or an Office Script. They run at the click of a button and have access to the Excel object model, i.e., they can insert a new sheet, format an Excel range as a table, set the color of a cell, etc.

Basic syntax

A script is a Python function that:

  • has the @script decorator

  • has a function argument with the xw.Book type hint

Here is how this looks:

import xlwings as xw
from xlwings import script

@script
def hello_world(book: xw.Book):
    sheet = book.sheets[0]
    sheet["A1"].value = "Hello xlwings!"

The book argument represents the active workbook and can be called differently if you like. E.g., if you want to call the argument wb instead of book, you would write: wb: xw.Book as the function’s argument.

Running a Script

To run a script, i.e., a function with the @script decorator, click on the run button or press F5:

_images/script_button.png

To select a different script to run, select it via dropdown:

_images/script_button_dropdown.png

Whenever you add a new script or change the name of an existing script, the button and dropdown will update automatically.

Excel Object Model

To learn about the Excel object model, have a look at the following docs from xlwings:

It’s also worth looking at the following tutorials:

Limitations

Currently, custom scripts don’t accept arguments other than book: xw.Book.