Archive

How to use Application.Undo in the xlwings API way

The Application.Undo method in Excel’s object model provides a way to reverse the last user-interface action performed in Excel, such as typing in a cell, formatting, or deleting data. In xlwings, this functionality is exposed through the api property, which grants direct access to the underlying Excel COM object. This allows Python scripts to mimic the “Undo” command typically executed by pressing Ctrl+Z, offering a mechanism to revert unintended changes programmatically. It is important to note that the Undo method is primarily designed for actions initiated through the Excel interface and may not work for changes made via VBA or COM automation in certain contexts. However, when called immediately after a user-style action performed via xlwings (like writing a value via the Excel interface), it can be effective.

The syntax for invoking the Undo method in xlwings is straightforward, as it does not take any parameters. The call is made through the Application object accessed from an xlwings App or Book instance. The general format is:

app.api.Undo()

Here, app refers to the xlwings App object representing the Excel application instance. The api property provides the native Excel Application COM object, and Undo() is the method call. No arguments are required or accepted. The method will reverse the last action if an undo history is available; otherwise, it may have no effect or raise an error in some scenarios.

For example, consider a scenario where a user manually types a value into a cell in an open Excel workbook, and then a script needs to undo that action. The following xlwings code demonstrates this:

import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Assume a user just typed "Test" into cell A1 of the active sheet manually
# To undo that entry programmatically:
app.api.Undo()

# This will revert the change in cell A1, restoring its previous value or clearing it if it was empty.

Another example involves performing an action through xlwings that mimics user interaction, followed by an undo. Note that not all xlwings operations populate the undo stack, as many bypass the UI. However, using Range.value setter might be treated as a user action in some contexts. A more reliable approach is to simulate keystrokes or use SendKeys, but a simpler method is to leverage Excel’s Application.Run to execute a macro that performs the action, which can then be undone. Below is an illustrative code snippet that writes a value using the Excel interface via Application.Run and then undoes it:

import xlwings as xw

app = xw.apps.active
wb = app.books.active
sheet = wb.sheets[0]

# Use Application.Run to execute a VBA-like operation that can be undone
# First, define a simple VBA function in a module (this requires VBA access; alternatively, use a pre-existing macro)
# For demonstration, assume a macro named "WriteValue" exists that writes to cell B2.
# Since xlwings can run macros, we can call it and then undo.
wb.api.Run("WriteValue") # This macro might set cell B2 to "Hello"
app.api.Undo() # This should undo the macro's action, reverting cell B2

How to use Application.SharePointVersion in the xlwings API way

The SharePointVersion property of the Application object in Excel’s object model provides a read-only integer value that indicates the version of Microsoft SharePoint Foundation or Microsoft SharePoint Server that the current workbook is linked to, if it is stored on a SharePoint site. This property is particularly useful for developers who need to programmatically determine the SharePoint environment to implement version-specific features or compatibility checks when automating Excel through xlwings. In xlwings, this property is accessed via the api property, which exposes the underlying Excel object model.

Functionality:
The primary function is to identify the SharePoint version, enabling conditional logic in macros or scripts. For instance, certain features or methods may behave differently across SharePoint versions, and knowing the version allows for adaptive code. If the workbook is not stored on SharePoint, the property typically returns 0.

Syntax in xlwings:
The property is accessed through the Application object. In xlwings, after establishing a connection to Excel (usually via app = xw.App() or xw.Book), you can retrieve the value as follows:

import xlwings as xw

# Connect to the active Excel instance or create a new one
app = xw.apps.active # or xw.App() for a new instance
sharepoint_version = app.api.SharePointVersion
  • Parameters: The SharePointVersion property does not take any parameters.
  • Return Value: It returns an integer representing the SharePoint version. Common values include:
  • 0: The workbook is not stored on a SharePoint site, or SharePoint is not detected.
  • 14: Corresponds to SharePoint 2010.
  • 15: Corresponds to SharePoint 2013.
  • 16: Corresponds to SharePoint 2016 or SharePoint Online (Office 365).
  • Other integer values may represent different or future versions.

Example Usage:
Below is a practical xlwings code example that checks the SharePoint version and performs actions based on the result. This example assumes Excel is already running with a workbook open, possibly from a SharePoint location.

import xlwings as xw

def check_sharepoint_version():
# Get the active Excel application
app = xw.apps.active

# Retrieve the SharePoint version
version = app.api.SharePointVersion

# Display or use the version information
if version == 0:
    print("This workbook is not stored on SharePoint.")
elif version == 14:
    print("SharePoint 2010 detected. Implement compatibility for this version.")
# Add version-specific code here, e.g., adjust data connection settings
elif version == 15:
    print("SharePoint 2013 detected. Features for this version are available.")
elif version == 16:
    print("SharePoint 2016 or SharePoint Online detected. Use modern APIs.")
else:
    print(f"Unknown SharePoint version: {version}. Check for updates.")

# You can also use the value in conditional logic for further automation
if version >= 16:
# Example: Enable newer SharePoint integration features
    print("Proceeding with advanced SharePoint functionalities.")
    return version

# Run the function
if __name__ == "__main__":
    sharepoint_ver = check_sharepoint_version()
    print(f"SharePoint Version Code: {sharepoint_ver}")

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.

How to use Application.Run in the xlwings API way

The Application.Run method in Excel’s object model is a powerful tool for executing procedures, such as macros or user-defined functions, that are stored in Excel workbooks. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model. This allows Python scripts to interact with Excel in a manner similar to VBA, enabling the automation of complex tasks and the integration of custom VBA code with Python workflows.

Functionality:
The primary purpose of Application.Run is to run a specified macro or function. This can include macros defined in VBA modules, functions in add-ins, or procedures in other open workbooks. It is particularly useful for scenarios where you need to trigger existing VBA code from an external Python script, leveraging the strengths of both environments. For instance, you might use Python for data processing and analysis, then call a VBA macro to format the results or generate a specific report layout that is already built in Excel.

Syntax in xlwings:
In xlwings, you access this method via the Application object obtained from a workbook or app instance. The basic syntax is:

app.api.Run(Macro, Arg1, Arg2, ..., Arg30)

Where:

  • app: This is the xlwings App object (e.g., xw.App() or xw.apps.active).
  • Macro: A required string argument specifying the name of the macro or function to run. The name should be in the format "WorkbookName!MacroName" or "MacroName" if the macro is in the current workbook. For add-ins, you might use the add-in’s registered name.
  • Arg1, Arg2, ..., Arg30: Optional arguments that can be passed to the macro. You can provide up to 30 arguments, which correspond to the parameters expected by the VBA procedure. These arguments can be of various data types, such as strings, numbers, or arrays, and they are passed by value to the macro.

Example Usage:
Suppose you have an Excel workbook named Report.xlsm with a VBA macro named FormatData that takes two arguments: a range address as a string and a boolean for enabling headers. You can call this macro from Python using xlwings as follows:

import xlwings as xw

# Connect to the open instance of Excel or start a new one
app = xw.apps.active # Assumes Excel is already open with the workbook

# Specify the macro name with workbook reference
macro_name = "Report.xlsm!FormatData"

# Define arguments: range address and header flag
range_address = "A1:D100"
headers_enabled = True

# Run the macro with arguments
app.api.Run(macro_name, range_address, headers_enabled)

# Alternatively, if the macro is in the active workbook, you can use:
# app.api.Run("FormatData", range_address, headers_enabled)

How to use Application.Repeat in the xlwings API way

The Application.Repeat property in Excel, when accessed via the xlwings API, is a read-only property that returns a Boolean value indicating whether the last user-interface action (such as a command or operation) can be repeated. This property is part of the Excel Application object model and is useful for building macros or applications that need to check the repeatability of an action before attempting to execute it again, often in conjunction with the Repeat method.

Functionality
The Application.Repeat property checks if the last action performed by the user in Excel can be repeated. This is typically used in custom VBA macros or add-ins to provide feedback or enable/disable repeat functionality in a user interface. In xlwings, it allows Python scripts to interact with Excel’s state, enabling automation that responds to user actions or workflow conditions. For instance, you might use it to verify that a formatting change or data entry can be repeated before proceeding with a batch operation.

Syntax
In xlwings, the Repeat property is accessed through the app object, which represents the Excel Application. The syntax is straightforward since it is a property with no parameters:

app.api.Repeat

Here, app is an instance of the xlwings App class (e.g., created with xw.App() or xw.apps). The .api attribute provides direct access to the underlying Excel object model, allowing you to call properties like Repeat. The property returns a Boolean:

  • True: The last action can be repeated.
  • False: The last action cannot be repeated, or no action is available to repeat.

Example
Below is a code example demonstrating how to use the Application.Repeat property in xlwings. This script checks if the last user action in Excel is repeatable and prints a message accordingly. It also shows a practical scenario where you might conditionally execute a repeat operation.

import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active # Use the currently running Excel application

# Check if the last action can be repeated
repeat_status = app.api.Repeat

if repeat_status:
    print("The last action in Excel can be repeated.")
    # Optionally, you could use app.api.Repeat() to perform the repeat action
    # Note: app.api.Repeat() is a method that repeats the last action
    try:
        app.api.Repeat() # This repeats the last user-interface action
        print("Action repeated successfully.")
    except Exception as e:
        print(f"Error repeating action: {e}")
else:
    print("The last action in Excel cannot be repeated or no action is available.")

# Example with a specific action: Let's assume a user just formatted a cell
# We'll simulate checking after a potential action
# First, ensure we have a workbook and range
wb = app.books.active
sheet = wb.sheets.active
cell = sheet.range("A1")
cell.value = "Test"
cell.api.Font.Bold = True # Apply bold formatting as an action

# Now check the Repeat property after this formatting
repeat_status_after = app.api.Repeat
print(f"After formatting A1 as bold, Repeat status: {repeat_status_after}")

# In many cases, formatting actions are repeatable, so this might return True
# You can use this to automate repetitive tasks based on user actions

Notes

  • The Repeat property is often used in tandem with the Repeat method (app.api.Repeat()), which actually repeats the last action. However, the property only indicates feasibility without performing the action.
  • In xlwings, accessing app.api.Repeat directly mirrors the VBA Application.Repeat property, ensuring compatibility with Excel’s behavior.
  • The property may return False if no previous action exists or if the action is not repeatable (e.g., some dialog-based operations). Always handle potential errors when using the related method.
  • This property is primarily relevant for user-interface interactions; in automated scripts, its value depends on the last action performed, which could be from the script itself or manual user input.

How to use Application.RegisterXLL in the xlwings API way

The RegisterXLL member of the Application object in Excel is a method that loads and registers an Excel add-in (XLL) file. XLLs are dynamic-link libraries (DLLs) specifically designed for Excel, providing custom functions, commands, or features that extend Excel’s native capabilities. In xlwings, this method allows you to programmatically register an XLL add-in from your Python code, enabling the use of its functions within Excel. This is particularly useful for automating workflows that depend on custom add-ins or for ensuring that required add-ins are loaded before executing certain tasks.

Syntax in xlwings:

app.api.RegisterXLL(Filename)

Here, app is an instance of the xlwings App class, representing the Excel application. The .api property provides access to the underlying Excel object model. The RegisterXLL method takes one parameter:

  • Filename (string, required): The full path and file name of the XLL add-in to be registered. For example, r"C:\AddIns\MyFunctions.xll".

If the registration is successful, the method returns True; if it fails (e.g., due to an invalid file path or compatibility issues), it returns False.

Example:
Suppose you have an XLL add-in named FinancialTools.xll located in a network drive. The following xlwings code registers this add-in in Excel and then uses a custom function from it to calculate a value. This example assumes Excel is already running or will be started by xlwings.

import xlwings as xw
import os

# Start or connect to Excel
app = xw.App(visible=True)

# Define the path to the XLL file
xll_path = r"\\server\share\AddIns\FinancialTools.xll"

# Check if the file exists before attempting to register
if os.path.exists(xll_path):
# Register the XLL add-in
    success = app.api.RegisterXLL(xll_path)
    if success:
        print("Add-in registered successfully.")

        # Open a workbook (or use the active one)
        wb = app.books.open(r"C:\Data\Report.xlsx")

        # Use a custom function from the add-in, e.g., a user-defined function (UDF)    named "CalculateNPV"
        # This writes the formula into cell A1 of the first sheet
        wb.sheets[0].range("A1").formula = "=CalculateNPV(B1:B10, 0.1)"

        # Calculate to ensure the formula is evaluated
        wb.api.Calculate()

        # Read the result
        result = wb.sheets[0].range("A1").value
        print(f"Calculated NPV: {result}")
    else:
        print("Failed to register the add-in.")
else:
    print("XLL file not found.")

# Close the workbook and quit Excel (optional)
wb.close()
app.quit()

How to use Application.RecordMacro in the xlwings API way

The Application.RecordMacro method in Excel’s object model is a powerful feature for automating the recording of a sequence of actions into a VBA macro. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying COM object, allowing you to leverage Excel’s native methods. This is particularly useful for developers who need to programmatically initiate macro recording, such as in testing scenarios or when building tools that assist users in creating macros without manually clicking the record button.

Functionality:
The primary purpose of RecordMacro is to start the macro recorder in Excel. When invoked, it begins capturing user interactions (like cell edits, formatting changes, or menu selections) and translates them into VBA code. This recorded code can then be saved to a module for later execution. In an automation context, using RecordMacro via xlwings enables scripts to trigger this recording process seamlessly, integrating macro generation into larger Python-based workflows.

Syntax in xlwings:
The method is called through the Application object. In xlwings, you typically access this via the app object representing an Excel instance. The syntax is:

app.api.RecordMacro(BasicCode, XlmCode)
  • BasicCode (Optional, Variant): A string that specifies the VBA code to be used as the macro. If provided, Excel will use this code directly instead of recording actions. If omitted, Excel starts recording interactively.
  • XlmCode (Optional, Variant): A string that specifies Excel 4.0 macro language (XLM) code. This is rarely used in modern contexts and is primarily for backward compatibility. It can be omitted.

Both parameters are optional. If neither is supplied, Excel begins recording a macro normally, prompting the user to save it later. If BasicCode is provided, Excel writes that code to a new module without interactive recording.

Code Examples:
Below are practical examples demonstrating how to use RecordMacro with xlwings.

  1. Starting Interactive Macro Recording:
    This example opens Excel and initiates the macro recorder, which will capture subsequent manual actions.
import xlwings as xw

# Connect to a running Excel instance or start a new one
app = xw.apps.active or xw.App()

# Start recording a macro interactively
app.api.RecordMacro()

# At this point, perform actions in Excel (e.g., type in a cell)
# After completing actions, stop recording via Excel's UI or programmatically
# Note: Stopping recording programmatically isn't direct via RecordMacro; it requires sending keystrokes or using SendKeys.
  1. Providing Predefined VBA Code:
    Instead of interactive recording, you can supply VBA code directly. This example creates a macro that inserts a timestamp.
import xlwings as xw

app = xw.apps.active or xw.App()
vba_code = """
Sub InsertTimestamp()
ActiveCell.Value = Now()
End Sub
"""

# Record the macro using the provided code
app.api.RecordMacro(BasicCode=vba_code)

# This will create a macro named "InsertTimestamp" in a new module
# Save the workbook to retain the macro
app.books.active.save()
  1. Integrating with User Workflows:
    In a tool that guides users, you might combine RecordMacro with other xlwings features. For instance, after preparing a worksheet, you could start recording for custom user actions.
import xlwings as xw

app = xw.App(visible=True)
wb = app.books.add()
ws = wb.sheets[0]
ws.range("A1").value = "Start recording your macro below:"

# Prompt user and begin recording
input("Press Enter to start macro recording...")
app.api.RecordMacro()

print("Recording started. Perform actions in Excel, then stop recording manually.")

Important Notes:

  • When using RecordMacro without parameters, the recording must be stopped manually by the user (e.g., clicking the stop button in Excel). Automating the stop process is complex and may require simulating keystrokes via SendKeys or using Windows API calls, which is beyond xlwings’ core functionality.
  • The method is part of Excel’s COM interface; thus, it requires Excel to be running and may have limitations in headless environments. Ensure Excel is visible (visible=True) for interactive recording.
  • For advanced automation, consider generating VBA code directly via xlwings’ vba module or using Python to write to modules, as this offers more control than relying on recording.

How to use Application.Quit in the xlwings API way

The Application.Quit method in Excel’s object model is a critical command for programmatically closing the Excel application itself. When automating tasks using xlwings, a Python library that interacts with Excel via its COM API, the Quit method provides a clean and controlled way to terminate the Excel process, especially after a script has completed its operations. This is essential for resource management, ensuring that no hidden Excel instances remain running in the background, which could consume memory and system resources. In xlwings, this method is accessed through the App object, which represents the Excel application.

Functionality:
The primary function of Quit is to close the Microsoft Excel application. It is analogous to manually clicking the close button (the “X”) on the Excel window or selecting “Exit” from the File menu. When invoked, it prompts Excel to close all open workbooks. If there are any unsaved changes in any open workbook, Excel will typically display a dialog box asking the user to save, discard changes, or cancel the quit operation, unless this default behavior is overridden by other settings (like DisplayAlerts being set to False).

Syntax in xlwings:
The xlwings API provides a Pythonic way to call this method. The general syntax is:

app.quit()

Here, app is an instance of the xlwings.App class, representing a running Excel application. The quit() method does not take any parameters in its xlwings implementation. It’s a direct wrapper around the underlying COM Quit method.

Important Considerations and Parameters:
While the xlwings app.quit() method itself has no arguments, the behavior upon quitting is influenced by the state of Excel’s DisplayAlerts property and the Saved status of workbooks. To quit without being prompted to save, you can set DisplayAlerts to False before calling quit(). However, this will discard any unsaved changes without warning.

Related Settingxlwings AccessEffect on Quit
DisplayAlertsapp.display_alerts = FalseSuppresses save prompts; unsaved data is lost.
Workbook Saved Propertywb.saved = TrueMarks a workbook as saved, preventing a prompt for that specific book.

Code Examples:

  1. Basic Quit: This example starts Excel, creates a new workbook, and then closes the application. If the workbook has not been saved, a prompt will appear.
import xlwings as xw
# Start Excel and create a new workbook
app = xw.App(visible=True)
wb = app.books.add()
# ... perform some operations ...
# Quit Excel (may show save prompt)
app.quit()
  1. Quit Without Save Prompts: This example demonstrates how to force Excel to close immediately, discarding any unsaved changes by turning off alerts.
import xlwings as xw
app = xw.App(visible=True)
wb = app.books.add()
wb.sheets[0].range('A1').value = "Unsaved Data"
# Disable alert dialogs
app.display_alerts = False
# Quit Excel; no prompt will appear, and changes are lost
app.quit()
  1. Quit After Saving: A more controlled approach is to save workbooks explicitly before quitting.
import xlwings as xw
import os
app = xw.App(visible=True)
wb = app.books.add()
wb.sheets[0].range('A1').value = "Important Data"
# Save the workbook to a specific path
file_path = os.path.join(os.getcwd(), 'report.xlsx')
wb.save(file_path)
# Now it's safe to quit without prompts
app.quit()

How to use Application.OnUndo in the xlwings API way

The Application.OnUndo method in Excel’s object model is a powerful feature that allows developers to customize the text displayed on the Undo button in the Quick Access Toolbar and specify a macro to run when that Undo command is executed. This is particularly useful for creating custom undo sequences for complex operations that involve multiple steps or external data changes, going beyond Excel’s built-in undo stack. In xlwings, which provides a Pythonic interface to automate Excel, you can access this functionality through the Application object’s api property, which exposes the underlying COM object, enabling you to call VBA-compatible methods directly.

Functionality:
The primary function of OnUndo is to assign a custom undo procedure. When a user clicks the Undo button after your code has set this property, Excel will run the specified macro instead of performing a standard undo. This allows for tailored reversal of actions that might not be captured by Excel’s native undo history, such as modifications to external databases, specific formatting sequences, or multi-sheet operations. It essentially overrides the default undo behavior for the next undo action only.

Syntax in xlwings:
In xlwings, you interact with the OnUndo method via the COM API. The general syntax is:

app.api.OnUndo(Text, Procedure)
  • Text: A required String argument. This is the text that will appear on the Undo button (e.g., “Undo Custom Import”). It should clearly describe the action to be reversed.
  • Procedure: A required String argument. This is the name of the macro (a VBA subroutine) that Excel will execute when the Undo button is clicked. The macro must be stored in a code module of the workbook.

Important Notes on Parameters:

  1. The Procedure must be a macro accessible in the workbook. In an xlwings context, you can write UDFs (User Defined Functions) or macros in VBA modules that are called from Python, but the OnUndo method itself calls VBA code. Therefore, you typically need a VBA macro in place.
  2. The custom undo text remains active only for the next undo operation. After the user clicks Undo or performs another action, Excel reverts to its default undo text and behavior.
  3. This method does not work for undoing events that occur after the workbook is closed; it is session-specific.

Example Usage with xlwings:
Suppose you have a Python script using xlwings that imports data and performs a complex transformation. You want to provide an undo option that reverts this import. First, ensure you have a VBA macro named UndoCustomImport in a module of your workbook. This macro might clear the imported range or restore original values.

Here is a sample xlwings code snippet:

import xlwings as xw

# Connect to the active Excel instance or create one
app = xw.apps.active

# Connect to the specific workbook
wb = app.books['MyWorkbook.xlsm']

# Run your custom data import and processing code
# ... (e.g., clear a range, write new data from a DataFrame)

# Set the custom Undo text and procedure
app.api.OnUndo("Undo Data Import", "UndoCustomImport")

# Inform the user
print("Data import completed. You can undo this action using 'Undo Data Import' in Excel.")

How to use Application.OnTime in the xlwings API way

The OnTime method in Excel’s Application object is a powerful feature for scheduling the execution of a procedure at a specific future time or after a specific time interval. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model. This allows for the automation of repetitive tasks, data refreshes, or timed notifications without user intervention, effectively enabling time-driven macros within a Python-controlled Excel environment.

Functionality:
The primary function is to run a specified VBA macro (procedure) at a predetermined time. It can be used for one-time execution or to set up recurring schedules. While xlwings itself runs Python code, OnTime schedules the execution of VBA macros stored in the Excel workbook. Therefore, typical use involves writing a VBA macro that, when triggered, can call back into Python via xlwings’ RunPython function or perform native Excel operations. This creates a hybrid automation model.

Syntax in xlwings:
The call is made through the Excel Application object. The syntax in xlwings is:

app.api.OnTime(EarliestTime, Procedure, LatestTime, Schedule)
  • EarliestTime (Required): The time when the procedure should be run. It is a serial Excel date/time value. In practice, it’s often created using datetime or time modules. Example: datetime.datetime.now() + datetime.timedelta(seconds=10).
  • Procedure (Required): A string specifying the name of the VBA macro to run. This macro must be present in a standard VBA module in the workbook (e.g., “Module1.MyMacro”).
  • LatestTime (Optional): The latest time for the procedure to run. If Excel is not in Ready, Copy, Cut, or Find mode at EarliestTime, it will wait until it enters one of these states, but only until LatestTime. If omitted, Excel waits indefinitely.
  • Schedule (Optional): A boolean value. True to schedule a new OnTime procedure (default). False to clear a previously set procedure that has not yet run.

Code Example:
This example schedules a VBA macro named “RefreshData” to run 5 seconds from now. The VBA macro itself could contain code to call a Python function or refresh queries.

import xlwings as xw
import datetime

# Connect to the active Excel instance or create a new one
app = xw.apps.active

# Calculate the time for execution (5 seconds from now)
run_time = datetime.datetime.now() + datetime.timedelta(seconds=5)

# Schedule the OnTime call. The macro "RefreshData" must exist in the workbook.
app.api.OnTime(EarliestTime=run_time, Procedure="RefreshData")

print(f"Scheduled 'RefreshData' to run at approximately {run_time}")

To cancel a scheduled procedure before it executes, you would call OnTime with the same EarliestTime and Procedure, but set Schedule to False:

# Cancel the previously scheduled "RefreshData" macro
app.api.OnTime(EarliestTime=run_time, Procedure="RefreshData", Schedule=False)