How to use Application.OnKey in the xlwings API way

The Application.OnKey member in Excel VBA allows developers to assign macros or specific actions to particular key combinations, effectively creating custom keyboard shortcuts. In xlwings, this functionality is exposed through the Application object’s on_key method, enabling Python scripts to dynamically set or clear these key bindings. This is particularly useful for building interactive Excel-based applications where certain keystrokes need to trigger automated processes, such as data refresh, formatting, or navigation.

Functionality:
Application.on_key in xlwings maps key combinations to callable Python functions or clears existing bindings. When the assigned key is pressed in Excel, the linked function executes, allowing for seamless integration of Python logic with user interactions. This can enhance productivity by automating repetitive tasks directly from the keyboard.

Syntax:
In xlwings, the method is accessed via app.api.OnKey, where app is an instance of xlwings.App. The syntax follows:

app.api.OnKey(Key, Procedure)
  • Key (required): A string specifying the key combination. Use codes like "^c" for Ctrl+C or "+{F1}" for Shift+F1. For special keys, enclose in braces (e.g., "{ENTER}"). See the table below for common codes.
  • Procedure (optional): A string naming the macro to run, or a callable Python function (via app.macro). If omitted or set to "", the key binding is cleared.

Key Code Examples:

CombinationCode
Ctrl+A"^a"
Alt+F4"%{F4}"
Shift+Tab"+{TAB}"
Enter"{ENTER}"

Example Usage:
Below are xlwings code snippets demonstrating Application.on_key:

  1. Assign a Python function to Ctrl+Shift+D:
import xlwings as xw

def custom_action():
wb = xw.books.active
wb.sheets[0].range("A1").value = "Shortcut triggered!"

app = xw.apps.active
# Use app.macro to wrap the Python function
app.api.OnKey("^+d", app.macro("custom_action"))

Pressing Ctrl+Shift+D in Excel will write the message to cell A1.

  1. Clear a key binding:
app.api.OnKey("^+d", "")

This removes the shortcut for Ctrl+Shift+D.

  1. Bind a simple key to an Excel macro:
app.api.OnKey("{F5}", "MyMacro")

Assumes “MyMacro” is a VBA macro stored in the workbook. Pressing F5 runs it.

April 15, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *