Archive

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)

How to use Application.OnRepeat in the xlwings API way

The Application.OnRepeat property in Excel VBA is used to assign a macro name (as a string) that will be executed when a user clicks the “Repeat” command. This command is typically available after performing an action that can be repeated, such as via the toolbar or the shortcut Ctrl+Y. In the context of xlwings, which provides a programmatic bridge between Python and Excel’s object model, this property can be accessed and manipulated to automate repetitive tasks within an Excel session. However, it’s important to note that xlwings primarily interacts with Excel through its API, and while it can execute VBA code, directly setting the OnRepeat property is not a standard, out-of-the-box feature because it is deeply tied to the VBA environment and the user interface. Typically, xlwings focuses on data manipulation, analysis, and automation using Python, leaving UI-specific commands like OnRepeat to be handled within VBA if necessary.

Functionally, OnRepeat allows for the customization of what action is repeated, enabling developers to define a specific macro for repetition, which can enhance user efficiency. In xlwings, to work with this property, you would need to use the api property of an xlwings App or Book object to access the underlying Excel Application object from the COM interface. This gives you direct access to VBA properties and methods, including OnRepeat.

The syntax for accessing the OnRepeat property via xlwings is through the Application object’s COM interface. Here’s the general format:

import xlwings as xw

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

# Access the OnRepeat property
repeat_macro = app.api.OnRepeat # Get the current value
app.api.OnRepeat = "MacroName" # Set the value to a macro name
  • app: This is an xlwings App object representing the Excel application.
  • api: This property provides access to the pywin32 COM object, which mirrors the Excel Application object from the VBA object model.
  • OnRepeat: This property can be get or set. When getting, it returns a string representing the name of the macro assigned to the Repeat command. When setting, it assigns a macro name (as a string) to the Repeat command. The macro must exist in the workbook’s VBA project.
  • MacroName: A string specifying the name of the macro to be repeated. This macro should be defined in a VBA module within the workbook.

Note: The OnRepeat property is specific to the Excel Application session and may not persist after closing Excel. Also, it requires that macros are enabled in Excel, and the macro must be accessible (e.g., in a standard module).

Here is an example code instance using xlwings to set and use the OnRepeat property:

import xlwings as xw

# Assume Excel is open with a workbook containing a macro named 'RepeatFormatting'
wb = xw.books.active
app = wb.app

# Set the OnRepeat property to 'RepeatFormatting'
app.api.OnRepeat = "RepeatFormatting"

# To demonstrate, we can run the macro once via xlwings (if needed)
# First, ensure the macro is in a module. We can run it using the Run method:
app.api.Run("RepeatFormatting")

# Later, when the user clicks Repeat or presses Ctrl+Y, the 'RepeatFormatting' macro will execute again.

# To retrieve the current OnRepeat setting:
current_repeat = app.api.OnRepeat
print(f"The current Repeat macro is: {current_repeat}")

# To clear the OnRepeat property (set it to an empty string):
app.api.OnRepeat = ""

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.

How to use Application.NextLetter in the xlwings API way

The Application.NextLetter property in Excel, when accessed through the xlwings API, provides a way to programmatically open the next mail message in the Microsoft Outlook inbox that is related to the reviewed workbook. This is particularly useful in workflows where Excel workbooks are sent via email for review, and you need to cycle through responses directly from Excel. It mimics the functionality of the “Next” button in the “Reviewing” toolbar within Excel’s user interface.

In xlwings, you interact with this property through the app object, which represents the Excel Application. The property is read-only and returns a MailItem object from the Outlook object model, representing the next email. The basic syntax is straightforward:

next_mail = app.api.NextLetter

Here, app is your xlwings App instance. The .api attribute provides direct access to the underlying Excel object model, allowing you to use the NextLetter property. It’s important to note that this property only works if the workbook was originally sent for review via email and there are subsequent mail items in the inbox related to it. If there is no next mail message, accessing this property will typically raise an error or return None, so error handling is advisable.

Consider a scenario where you have an Excel workbook open that was part of an email review cycle. The following xlwings code example demonstrates how to use NextLetter to open the next related email and extract its subject line, showcasing integration with the win32com.client library to interact with Outlook’s properties:

import xlwings as xw
import win32com.client

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

try:
# Get the next mail item related to the reviewed workbook
    next_mail = app.api.NextLetter

    # To interact with the mail item's properties, you might use win32com
    # The NextLetter property returns a MailItem object
    # We can use win32com.client.Dispatch to access it if needed,
    # but note: app.api.NextLetter already returns a COM object for the mail.
    # Here, we directly access its Subject property.
    # In practice, ensure Outlook is accessible.
    mail_subject = next_mail.Subject
    print(f"Next email subject: {mail_subject}")

    # You can then display the email, for example:
    next_mail.Display(True) # Opens the email in Outlook for viewing

except AttributeError as e:
    print("No next mail item found or property not available.")
except Exception as e:
    print(f"An error occurred: {e}")

How to use Application.MailLogon in the xlwings API way

The MailLogon member of the Application object in Excel’s object model is a method that allows you to log on to a MAPI mail system programmatically. This functionality is useful when you need to automate email-related tasks, such as sending workbooks or reports directly from Excel via the default email client. In xlwings, you can access this method through the Application object, enabling you to integrate email operations into your Python scripts for enhanced automation and productivity. Note that this method relies on the underlying MAPI (Messaging Application Programming Interface) system, so it requires a compatible email client like Microsoft Outlook to be installed and configured on the machine.

The syntax for calling the MailLogon method via xlwings is as follows:

app.api.MailLogon(Name, Password, DownloadNewMail)

Here, app refers to the xlwings Application object, typically obtained using xw.App() or xw.apps.active. The parameters are:

  • Name (optional, Variant): A string specifying the mail profile name. If omitted, the default profile is used.
  • Password (optional, Variant): A string for the mail password. If omitted, the stored password is used if available.
  • DownloadNewMail (optional, Variant): A Boolean value that determines whether new mail is downloaded upon logon. Set to True to download new mail, or False otherwise. The default is True.

The parameters can be passed by position or as keyword arguments. For example, to log on with a specific profile and download new mail, you might use app.api.MailLogon("MyProfile", "mypassword", True). It’s important to handle security and password storage carefully in scripts to avoid exposing sensitive information.

Below is a code example demonstrating the use of MailLogon with xlwings. This example assumes Excel and a MAPI-compliant email client are running, and it logs on to a mail profile before performing a simple email-related task, such as sending the active workbook. Note that in practice, you should ensure proper error handling and user authentication.

import xlwings as xw

# Start or connect to an Excel application
app = xw.App(visible=True) # Set visible=False for background operation

# Open a workbook (optional, for context)
wb = app.books.open('example.xlsx')

# Log on to the mail system using MailLogon
try:
# Using default profile and downloading new mail
    app.api.MailLogon(DownloadNewMail=True)
    print("Logged on to mail system successfully.")

    # Example: Send the active workbook as an email attachment
    # This uses the Mailer object via the Workbook's Mailer property (deprecated in newer Excel versions)
    # For modern email automation, consider using Outlook's COM object or other libraries
    wb.api.Mailer.Send()
    print("Workbook sent via email.")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
# Clean up: Log off from mail and close Excel
    app.api.MailLogoff()
    wb.close()
    app.quit()

How to use Application.MailLogoff in the xlwings API way

The Application.MailLogoff method in Excel is used to log the user off from an email system (such as Microsoft Outlook) that has been previously logged into through Excel. This is particularly relevant when using Excel’s email features, like sending workbooks via email programmatically. In xlwings, which provides a Pythonic way to automate Excel, you can access this method through the Application object to manage email sessions cleanly, ensuring resources are released and sessions are properly closed after email operations.

Functionality
The primary function of MailLogoff is to terminate an active email session that was initiated via Excel. This is useful in automation scripts where you send emails from Excel and want to log out afterward to prevent issues like multiple open sessions or security concerns. It does not take any parameters and simply ends the session. Note that this method is part of the Excel object model and may not be frequently used in modern automation, as many developers prefer direct email libraries (e.g., smtplib in Python), but it remains available for compatibility with Excel-based email workflows.

Syntax
In xlwings, you call MailLogoff through the Application object. The syntax is straightforward since it has no arguments:

app.xl_app.MailLogoff()

Here, app refers to an xlwings App instance representing the Excel application. xl_app is the underlying COM object (via pywin32 on Windows or appscript on macOS) that exposes the Excel Application object from the Excel object model. The method is invoked without any parameters.

Example
Below is a complete xlwings code example that demonstrates logging into an email session (using MailLogon, which is often paired with MailLogoff) and then logging off. This example assumes you have Excel and an email client like Outlook set up. Note that MailLogon may require credentials, but in practice, it often uses the current user’s default profile.

import xlwings as xw

# Start an Excel application instance
app = xw.App(visible=False) # Set visible=True to see Excel

try:
# Log into email (this might trigger a login prompt or use default credentials)
# In some cases, MailLogon may not be needed if a session is already active
    app.xl_app.MailLogon(Name="YourName", Password="YourPassword",    DownloadNewMail=False)
    print("Logged into email successfully.")

    # Perform email-related tasks, e.g., send a workbook via email
    # (Code for sending email would go here, but is omitted for brevity)

    # Log off from the email session
    app.xl_app.MailLogoff()
    print("Logged off from email.")

except Exception as e:
    print(f"An error occurred: {e}")

finally:
# Close the Excel application
    app.quit()

How to use Application.MacroOptions in the xlwings API way

The MacroOptions member of the Application object in Excel’s object model provides a way to configure settings related to macros, particularly the Macro Recorder. This is useful for developers who need to programmatically control how macros are recorded, such as setting the description, shortcut key, or category for a newly recorded macro. While the primary interface is through Excel VBA, xlwings allows you to access and manipulate this functionality from Python, enabling automation of macro-related setups in Excel workbooks.

In xlwings, you can access the MacroOptions method through the api property of an App or Book object, which exposes the underlying Excel object model. The syntax for calling MacroOptions in xlwings closely mirrors its VBA counterpart, but adapted for Python. The general format is:

app.api.MacroOptions(Macro, Description, HasMenu, MenuText, HasShortcutKey, ShortcutKey, Category, StatusBar, HelpContextID, HelpFile)

Here, app is an instance of xlwings.App, representing the Excel application. The parameters are optional and correspond to the settings you can configure for a macro. Below is a table detailing each parameter:

ParameterTypeDescriptionDefault Value in xlwings (if omitted)
MacroStringThe name of the macro (e.g., “MyMacro”).Required; no default.
DescriptionStringA description for the macro.None (ignored).
HasMenuBooleanTrue to add the macro to a menu; False otherwise.None (ignored).
MenuTextStringThe text to display in the menu if HasMenu is True.None (ignored).
HasShortcutKeyBooleanTrue to assign a shortcut key; False otherwise.None (ignored).
ShortcutKeyStringThe shortcut key (e.g., “Ctrl+Shift+M”).None (ignored).
CategoryStringThe category for the macro (e.g., “Custom Functions”).None (ignored).
StatusBarStringText to display in the status bar when the macro is selected.None (ignored).
HelpContextIDLongThe context ID for Help.None (ignored).
HelpFileStringThe path to the Help file.None (ignored).

In practice, you can use this method to set options for an existing macro or to pre-configure settings before recording. For example, to set a description and shortcut key for a macro named “TestMacro” in an active Excel workbook, you can write the following xlwings code:

import xlwings as xw

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

# Configure macro options for "TestMacro"
app.api.MacroOptions(
Macro="TestMacro",
Description="This macro performs a data cleanup operation.",
HasShortcutKey=True,
ShortcutKey="Ctrl+Shift+T"
)