How to use Application.SendKeys in the xlwings API way

The SendKeys member of the Application object in Excel is a powerful method for simulating keystrokes directly to the active application window, typically Excel itself. In xlwings, this functionality is exposed through the api property, allowing you to programmatically send key combinations that would normally be entered manually. This can be used to automate tasks like opening menus, triggering shortcuts, or interacting with dialog boxes, especially when other programmatic methods are limited. It’s particularly useful for legacy automation scenarios where UI interaction is required.

Syntax in xlwings:
The syntax follows the Excel Object Model via the xlwings api:

app.api.SendKeys(Keys, Wait)
  • Keys: A string expression specifying the keystrokes to send. Use codes like "{F5}" for function keys, "^c" for Ctrl+C, or "%f" for Alt+f. Special keys are enclosed in braces (e.g., "{ENTER}", "{TAB}"). To send literal characters, simply type them.
  • Wait: Optional Boolean. If True, Excel waits for the keys to be processed before continuing. If False or omitted, the macro continues immediately without waiting. Default is False.

Key Code Examples:

Key CombinationCode String
Enter"{ENTER}"
Ctrl+A"^a"
Alt+F4"%{F4}"
Shift+Tab"+{TAB}"
Page Down"{PGDN}"

Examples in xlwings:

  1. Activate the Find Dialog (Ctrl+F):
import xlwings as xw
app = xw.apps.active # Get the active Excel application
app.api.SendKeys("^f") # Send Ctrl+F to open Find
  1. Refresh All Data Connections (Alt+F5):
app.api.SendKeys("%{F5}", Wait=True) # Alt+F5 and wait for completion
  1. Navigate and Select a Cell Range:
app.api.SendKeys("{F5}") # Open Go To dialog
app.api.SendKeys("A1:D10{ENTER}") # Type range and press Enter
  1. Close the Active Workbook with Save Prompt (Alt+F, then C):
app.api.SendKeys("%fc") # Alt+F to open File menu, then C for Close
# Note: This may interact with save dialogs; handle with caution.

April 20, 2026 (0)


Leave a Reply

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