Archive

How to use Application.DDEAppReturnCode in the xlwings API way

The DDEAppReturnCode property of the Application object in Excel is a read-only property that returns the status code from the last Dynamic Data Exchange (DDE) operation. DDE is an older inter-process communication protocol that allows applications to exchange data. While modern automation typically uses other methods like COM (which xlwings utilizes), this property can be useful for debugging or maintaining legacy Excel applications that interact with DDE servers. The returned integer code indicates success or the specific type of error that occurred during the DDE conversation.

In xlwings, you access this property through the api property of the main App or Book objects, which exposes the raw Excel VBA object model. The syntax is straightforward as it takes no arguments.

Syntax:

xlwings.App.api.DDEAppReturnCode

or, if you have a specific workbook instance:

wb.api.Application.DDEAppReturnCode

Where:

  • The property is accessed directly and returns an Integer value.

The meaning of the return codes is defined by the DDE protocol and the applications involved. Common codes include:

CodeTypical Meaning
0Success / No Error
1The topic was not understood by the server.
2The server did not respond.
7Unknown error.

Important Note: The exact meaning of non-zero codes can vary depending on the DDE server application. You should consult the documentation for the specific application you are communicating with.

Example:
The following xlwings code initiates a DDE operation (a very legacy example) and then checks the return code to see if it was successful.

import xlwings as xw

# Start Excel application
app = xw.App(visible=False)
wb = app.books.add()

# Attempt a legacy DDE operation (e.g., initiating a conversation with "MyServer" on topic "System")
# Note: This is a pseudo-example, as modern xlwings doesn't have direct DDE methods.
# You would typically use the Excel VBA object model via .api for such calls.
try:
    # Simulating a DDE operation using the Excel object model
    # In VBA, this might be: channel = Application.DDEInitiate(app:="MyServer", topic:="System")
    # In xlwings, you would use:
    channel = app.api.DDEInitiate("MyServer", "System")
    print(f"DDE channel opened: {channel}")
except Exception as e:
    print(f"An error occurred during DDEInitiate: {e}")
finally:
    # Check the status code of the last DDE operation
    return_code = app.api.DDEAppReturnCode
    print(f"DDEAppReturnCode: {return_code}")

# Interpret the code
if return_code == 0:
    print("Last DDE operation was successful.")
else:
    print(f"Last DDE operation failed with error code: {return_code}")

# Clean up: Close the channel if it was opened, then quit Excel
if 'channel' in locals():
    app.api.DDETerminate(channel)
wb.close()
app.quit()

How to use Application.DataEntryMode in the xlwings API way

In Excel VBA, the Application.DataEntryMode property is a legacy feature that determines whether Excel is in data entry mode. When enabled, Excel restricts user interaction to only the active data form, preventing access to other parts of the workbook. This is particularly useful for creating controlled data input interfaces, such as custom forms, where you want to limit user actions to specific fields. However, it’s important to note that this property is part of the older Excel object model and may not be widely used in modern applications, as more advanced methods like UserForms or custom dialog boxes are now preferred for data entry tasks.

In xlwings, which provides a Pythonic interface to Excel’s object model, you can access the DataEntryMode property through the Application object. The syntax for accessing this property is straightforward, as it is a read-write property that returns or sets an integer value representing the data entry mode. The values are typically: 0 for normal mode (not in data entry) and 1 for data entry mode. However, the exact behavior and supported values might vary depending on the Excel version, so it’s advisable to refer to Microsoft’s official documentation for detailed specifications.

To use Application.DataEntryMode in xlwings, you first need to establish a connection to an Excel instance or a specific workbook. Here’s the basic syntax:

import xlwings as xw

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

# Get the current data entry mode
current_mode = app.api.DataEntryMode
print(f"Current DataEntryMode: {current_mode}")

# Set the data entry mode to 1 (enable data entry mode)
app.api.DataEntryMode = 1

# Perform data entry tasks, then disable data entry mode
app.api.DataEntryMode = 0

In this code, app.api.DataEntryMode is used to interact with the property. The .api attribute in xlwings provides direct access to the underlying Excel object model, allowing you to use properties and methods as defined in VBA. When setting the property, ensure that you are in a context where data entry mode is applicable, such as when a data form is active. Otherwise, setting it might not have any effect or could lead to unexpected behavior.

For a practical example, suppose you are automating a data entry process in Excel where you want to lock the interface to a specific form. You can enable data entry mode to restrict user interactions. Here’s a sample code snippet:

import xlwings as xw
import time

# Start Excel and open a workbook
wb = xw.Book('data_entry.xlsx')
app = wb.app

# Assume a data form is active; enable data entry mode
app.api.DataEntryMode = 1
print("Data entry mode enabled. User restricted to the active form.")

# Simulate data entry tasks, such as filling fields
# For demonstration, wait for 5 seconds to mimic user input
time.sleep(5)

# Disable data entry mode after completion
app.api.DataEntryMode = 0
print("Data entry mode disabled. Normal interaction restored.")

# Save and close the workbook
wb.save()
wb.close()

How to use Application.CutCopyMode in the xlwings API way

The Application.CutCopyMode property in Excel VBA is a property of the Application object that returns or sets the status of the Cut or Copy mode. This property is useful for programmatically determining if a cut or copy operation is currently active, or to cancel such an operation. In xlwings, this property is accessed through the api property of the App object, which provides direct access to the underlying Excel object model. Understanding this property is essential for automating tasks that involve clipboard operations, ensuring that your macros run without interference from pending cut/copy actions.

Functionality:
The primary function of the CutCopyMode property is to manage the state of cut and copy operations within Excel. It can have three possible values:

  • False (or 0): Indicates that no cut or copy operation is currently in progress.
  • True (or 1): Indicates that a copy operation is active. The source range is highlighted with a moving border.
  • xlCut (or 2): Indicates that a cut operation is active. The source range is also highlighted.

By reading this property, your script can check for an active operation before performing actions that might conflict, such as pasting or clearing the clipboard. Setting this property to False is the programmatic equivalent of pressing the ESC key, which cancels the moving border and clears the clipboard state.

Syntax in xlwings:
In xlwings, you interact with this property via the Excel Application object’s COM interface.

  • To Get the current mode:
    current_mode = xw.apps[<app_index>].api.CutCopyMode
    This returns an integer corresponding to the current state.
  • To Set the mode (typically to cancel):
    xw.apps[<app_index>].api.CutCopyMode = False

Parameter & Return Values:
The property is read/write. Its value can be set or returned as a Long integer or a Boolean. The standard values are:

ValueConstant (VBA)Description
0FalseNo cut or copy mode is active.
1TrueCopy mode is active.
2xlCutCut mode is active.

When setting the property, only False (0) is typically used to cancel the mode. Attempting to set it to True or xlCut does not initiate a new cut/copy operation.

Code Examples:

  1. Checking and Reporting the Current Mode:
    This example checks the status and prints a descriptive message.
import xlwings as xw

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

# Get the current CutCopyMode
mode = app.api.CutCopyMode

if mode == 0:
    print("No cut or copy operation is active.")
elif mode == 1:
    print("A copy operation is in progress.")
elif mode == 2:
    print("A cut operation is in progress.")
else:
    print(f"Unknown mode value: {mode}")
  1. Cancelling an Active Cut/Copy Operation:
    This is a common practice to ensure a clean state before executing other operations.
import xlwings as xw

app = xw.apps.active

# Check if a cut/copy mode is active
if app.api.CutCopyMode:
    print("Cancelling the active cut/copy mode.")
    app.api.CutCopyMode = False # Equivalent to pressing ESC

# Now it's safe to proceed, e.g., with a paste operation
# app.api.Selection.PasteSpecial() # Example follow-up action
  1. Integrating into a Larger Workflow:
    This example copies a range, performs a check, and then cancels the mode.
import xlwings as xw

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

# Perform a copy operation (this activates Copy mode)
sheet.range("A1:B2").copy()

# Verify the mode was activated
if app.api.CutCopyMode == 1:
    print("Range copied successfully. Copy mode is active.")

# ... Perform other tasks ...

# Cancel the copy mode explicitly when done
app.api.CutCopyMode = False
print("Copy mode cleared.")

How to use Application.CustomListCount in the xlwings API way

The CustomListCount member of the Application object in Excel refers to the total number of custom lists available in the Excel application. Custom lists are user-defined sequences (e.g., a list of department names, product categories, or regional offices) that can be used for autofill and sorting operations. This property is read-only and returns a Long integer representing the count. In xlwings, you can access this property to programmatically determine how many custom lists are currently defined, which is useful for automating tasks that depend on these lists, such as data validation or dynamic range naming based on list entries.

Syntax in xlwings:
The property is accessed through the Application object. In xlwings, you typically start by instantiating an app or using the active app. The syntax is straightforward:

app.custom_list_count

Here, app is an instance of the xlwings App class, representing the Excel application. The property takes no parameters and directly returns an integer value. For example, if you have defined three custom lists in Excel (e.g., “Q1, Q2, Q3, Q4”, “East, West, North, South”, and “Low, Medium, High”), calling app.custom_list_count will return 3.

Example Usage:
Below is a practical xlwings code example that demonstrates how to use the CustomListCount property. This example checks the number of custom lists and prints a message based on the count. It also shows how to iterate through custom lists if needed (though note that accessing individual list details requires other properties like CustomList, which is not covered here as per the focus on CustomListCount).

import xlwings as xw

def check_custom_lists():
# Connect to the active Excel instance or start a new one
app = xw.apps.active # Use the currently active Excel application

# Get the count of custom lists
count = app.custom_list_count

# Output the result
print(f"Number of custom lists available: {count}")

# Example logic based on the count
if count == 0:
    print("No custom lists are defined. Consider creating some for autofill or sorting tasks.")
elif count <= 5:
    print("A moderate number of custom lists are available. Suitable for basic automation.")
else:
    print("Many custom lists are available. Ideal for complex data processing workflows.")

# Optional: Close the app if it was started by xlwings (uncomment if needed)
# app.quit()

# Run the function
if __name__ == "__main__":
check_custom_lists()

How to use Application.CursorMovement in the xlwings API way

In the xlwings library, the Application object’s CursorMovement property provides control over the movement of the cell cursor after pressing the Enter key in Microsoft Excel. This property is particularly useful for customizing user interaction within a workbook, enhancing data entry efficiency by dictating the direction in which the selection moves post-data entry.

Functionality:
The CursorMovement property determines the direction in which the active cell moves when the Enter key is pressed. This can be set to move down, up, left, or right, depending on the user’s preference or the specific workflow requirements. By default, Excel moves the cursor down, but this can be adjusted programmatically via xlwings to streamline repetitive data entry tasks, such as filling rows horizontally or navigating vertically in a structured manner.

Syntax:
In xlwings, the CursorMovement property is accessed through the Application object. The property can be both read and set. The syntax is as follows:

app = xw.App()
app.api.CursorMovement

Here, app.api provides access to the underlying Excel object model. The CursorMovement property accepts integer values that correspond to specific movement directions, as defined in the Excel enumeration xlDirection. The primary values are:

  • xlDown (value: -4121): Moves the cursor down.
  • xlUp (value: -4162): Moves the cursor up.
  • xlToLeft (value: -4159): Moves the cursor to the left.
  • xlToRight (value: -4161): Moves the cursor to the right.

To set the property, assign one of these integer values. For example, to move the cursor to the right, use:

app.api.CursorMovement = -4161 # xlToRight

Example Usage:
Below are practical xlwings code examples demonstrating how to use the CursorMovement property:

  1. Setting Cursor Movement to Move Right:
    This example opens an Excel workbook and configures the cursor to move right after pressing Enter, which is useful for entering data across rows.
import xlwings as xw
app = xw.App(visible=True)
workbook = app.books.open('example.xlsx')
app.api.CursorMovement = -4161 # Set to move right
print(f"Cursor movement set to: {app.api.CursorMovement}")
# Perform data entry or other operations
app.quit()
  1. Reading and Changing Cursor Movement Dynamically:
    This example reads the current cursor movement setting, changes it based on a condition, and then restores the original setting.
import xlwings as xw
app = xw.App(visible=False)
original_movement = app.api.CursorMovement
print(f"Original cursor movement: {original_movement}")

if original_movement == -4121: # If currently moving down
    app.api.CursorMovement = -4162 # Change to move up
    print("Cursor movement changed to move up.")
else:
    app.api.CursorMovement = -4121 # Default to move down
    print("Cursor movement changed to move down.")

# Restore original setting after operations
app.api.CursorMovement = original_movement
app.quit()
  1. Using Cursor Movement in a Data Entry Loop:
    This example simulates a data entry scenario where the cursor movement is set to move down, and then a loop enters sample data into a column.
import xlwings as xw
app = xw.App(visible=True)
workbook = app.books.add()
sheet = workbook.sheets[0]
app.api.CursorMovement = -4121 # Move down

# Enter data into cells A1 through A5
for i in range(1, 6):
    sheet.range(f'A{i}').value = f'Data {i}'
    # In a real scenario, pressing Enter would move the cursor down automatically

print("Data entry complete with cursor moving down.")
app.quit()

How to use Application.Cursor in the xlwings API way

In the Excel object model, the Application.Cursor property is a member of the top-level Application object, which represents the entire Excel application. This property controls the visual appearance of the mouse cursor (pointer) in Excel. It is particularly useful in automation scenarios where you want to provide visual feedback to users, such as indicating that a long-running operation is in progress. By changing the cursor, you can enhance the user experience by signaling that the application is busy or that a specific action is required.

Functionality:
The Application.Cursor property allows you to get or set the mouse cursor shape displayed in Excel. It can be used to change the cursor to standard shapes like an arrow, an I-beam for text selection, or a wait cursor (e.g., an hourglass or spinning wheel) during lengthy operations. This helps in making automated processes more user-friendly by visually communicating the application’s state.

Syntax:
In xlwings, you can access the Application.Cursor property through the app object, which represents the Excel application. The property is used to get or set the cursor type. The syntax is as follows:

  • To get the current cursor: current_cursor = app.api.Cursor
  • To set the cursor to a new value: app.api.Cursor = cursor_value

Here, app is an instance of the xlwings App class, typically created with xw.App() or accessed via xw.apps. The api attribute provides direct access to the underlying Excel object model. The cursor_value is an integer or enumeration constant that specifies the cursor shape. In Excel VBA, these values are defined by the XlMousePointer enumeration. Common values include:

  • xlDefault (or 0): The default cursor (usually an arrow).
  • xlWait (or 1): A wait cursor (e.g., hourglass), indicating that Excel is busy.
  • xlIBeam (or 3): An I-beam cursor, used for text selection.
  • xlNorthwestArrow (or 2): A northwest arrow cursor.

To use these in xlwings, you can define constants or use the integer values directly. For example, xlWait corresponds to the integer 1.

Example:
Below is an xlwings code example that demonstrates how to use the Application.Cursor property to change the mouse cursor during a time-consuming operation, such as processing data in a worksheet. This example shows setting the cursor to a wait state, performing a task, and then resetting it to the default.

import xlwings as xw
import time

# Connect to the active Excel application or start a new one
app = xw.apps.active if xw.apps.active else xw.App()

# Set the cursor to wait (hourglass) to indicate busy state
app.api.Cursor = 1 # Using integer value for xlWait
print("Cursor set to wait state. Processing data...")

# Simulate a long-running task, e.g., iterating through cells
try:
    # Access the active workbook and worksheet
    wb = app.books.active
    ws = wb.sheets.active

    # Example operation: sum values in a range (this could be any intensive task)
total = 0
    for cell in ws.range("A1:A10"): # Process a range of cells
        if cell.value is not None:
            total += cell.value
            time.sleep(0.1) # Simulate delay for demonstration

            print(f"Total sum from A1:A10 is: {total}")

finally:
    # Always reset the cursor to default after the operation
    app.api.Cursor = 0 # Using integer value for xlDefault
    print("Cursor reset to default state.")

# Optional: Close the app if it was started in this script
# app.quit()

How to use Application.Creator in the xlwings API way

The Creator property of the Application object in Excel’s object model is a read-only attribute that returns a 32-bit integer representing the application that created the file. In Excel, this value is typically used to identify whether the file was created by Microsoft Excel or another application, such as a third-party tool or a different version of Excel. In xlwings, the Creator property can be accessed to retrieve this identifier, which can be useful for compatibility checks, file validation, or logging purposes when automating Excel tasks.

Functionality:
The Creator property helps determine the origin application of an Excel file. For instance, if a file was created by Excel, the Creator value will correspond to Microsoft Excel’s identifier. This can be essential in scenarios where you need to ensure that files are processed only from specific sources or to troubleshoot issues related to file creation.

Syntax in xlwings:
In xlwings, you can access the Creator property through the app object, which represents the Excel application. The syntax is straightforward, as it is a property without parameters. Here’s the general format:

creator_value = app.api.Creator
  • app: This is the xlwings App instance connected to Excel.
  • api: This attribute provides access to the underlying Excel object model, allowing direct interaction with properties like Creator.
  • Creator: The property that returns an integer representing the creator application.

The returned value is an integer. For Microsoft Excel, the typical value is 1480803660 (which corresponds to the hexadecimal 0x5843454C, representing “XCEL” in ASCII). Other applications may have different values. You can compare this integer to known constants to identify the creator.

Example Usage:
Below is a code example that demonstrates how to use the Creator property in xlwings to check if the current Excel file was created by Microsoft Excel. This example assumes you have an Excel application open and connected via xlwings.

import xlwings as xw

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

# Access the Creator property
creator_code = app.api.Creator

# Define known creator codes (example for Microsoft Excel)
EXCEL_CREATOR = 1480803660 # This is the standard value for Excel

# Check the creator and print the result
if creator_code == EXCEL_CREATOR:
    print("The file was created by Microsoft Excel.")
else:
    print(f"The file was created by another application. Creator code: {creator_code}")

# You can also convert the code to a hexadecimal string for easier interpretation
hex_creator = hex(creator_code)
print(f"Creator code in hexadecimal: {hex_creator}")

How to use Application.CopyObjectsWithCells in the xlwings API way

Application.CopyObjectsWithCells Property in xlwings

The Application.CopyObjectsWithCells property in Excel, accessible via the xlwings API, controls whether drawing objects (such as shapes, charts, pictures, and other embedded objects) are copied or moved along with their associated cells during cut, copy, or fill operations in a worksheet. This property is a global application-level setting, meaning it affects the behavior across all open workbooks in the Excel instance controlled by xlwings. It is particularly useful for automating tasks where you need to ensure that graphical elements remain attached to specific data ranges when those ranges are manipulated.

Syntax and Parameters in xlwings

In xlwings, you interact with this property through the app object, which represents the Excel Application. The property is exposed as a read/write Boolean attribute.

  • Property Access:
  • app.api.CopyObjectsWithCells (using the .api attribute to access the underlying Excel object model directly).
  • Alternatively, you can use app.engine.api.CopyObjectsWithCells if working with a specific engine context in more advanced scenarios, but typically the app.api route is standard.
  • Value:
  • True: (Default) Drawing objects are copied, moved, or filled along with cells.
  • False: Drawing objects remain in their original positions on the worksheet; only the cell contents and formats are affected by the operation.

Code Examples

Here are practical xlwings code snippets demonstrating how to get and set this property, and its impact on operations.

  1. Checking the Current Setting:
import xlwings as xw

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

# Get the current value of CopyObjectsWithCells
current_setting = app.api.CopyObjectsWithCells
print(f"CopyObjectsWithCells is currently set to: {current_setting}")
# Output will be True or False
  1. Changing the Setting and Performing a Copy Operation:
    This example disables the copying of objects, copies a cell range, and then restores the original setting.
import xlwings as xw

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

# Assume cell A1 has a shape (e.g., a rectangle) over it and contains the number 10.
original_setting = app.api.CopyObjectsWithCells

# Set to False: Objects will NOT move with cells.
app.api.CopyObjectsWithCells = False
print("Set CopyObjectsWithCells to False.")

# Copy cell A1 to B1. Only the value (10) will be copied.
sheet.range('A1').copy(sheet.range('B1'))

# Verify: B1 now contains 10, but the shape remains only over A1.

# Restore the original application setting
app.api.CopyObjectsWithCells = original_setting
print("Restored original setting.")
  1. Automating a Task with Controlled Object Behavior:
    A more integrated example where you temporarily enable object copying to duplicate a data section with its associated chart.
import xlwings as xw

app = xw.apps.active
wb = app.books['Report.xlsx']
data_sheet = wb.sheets['MonthlyData']

# Ensure objects are copied with cells for this specific operation
app.api.CopyObjectsWithCells = True

# Define the source range (A1:D10) which includes data and an embedded chart object
source_range = data_sheet.range('A1:D10')
# Define the target starting cell
target_range = data_sheet.range('A12')

# Copy the entire block, including the chart
source_range.copy(target_range)

# Optional: Reset to default (True) or a previous state if needed for other macros/users.
# app.api.CopyObjectsWithCells = False

How to use Application.ControlCharacters in the xlwings API way

The Application.ControlCharacters property in Excel’s object model is a member of the Application object that controls the display of certain control characters within cells. Specifically, it determines whether control characters (such as line breaks, carriage returns, or tab characters) are shown as visible symbols or are rendered as their functional effects (like actual line breaks). This property is particularly useful when dealing with text data imported from other systems that may contain these characters, allowing users to toggle their visibility for editing or debugging purposes. In xlwings, this property can be accessed and modified to customize how Excel handles these characters in the user interface.

In terms of syntax, the ControlCharacters property is accessed through the Application object in xlwings. The xlwings API provides a straightforward way to interact with this property using Python. The property is a Boolean value, where True means that control characters are displayed as visible symbols (e.g., a small square for a line break), and False means they are rendered normally (e.g., causing an actual line break in the cell). The xlwings call format follows the pattern of accessing properties from the app object, which represents the Excel application. For example, to get the current setting, you use app.api.ControlCharacters, and to set it, you assign a value like app.api.ControlCharacters = True. Note that app must be an instance of the xlwings App class connected to a running Excel application. This property does not take additional parameters; it is a simple read/write property that affects the entire Excel instance.

Here is a code example demonstrating the usage of Application.ControlCharacters with xlwings. First, ensure you have xlwings installed and an Excel workbook open. The example will toggle the display of control characters and print the current state:

import xlwings as xw

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

# Get the current ControlCharacters setting
current_setting = app.api.ControlCharacters
print(f"Current ControlCharacters setting: {current_setting}")

# Set ControlCharacters to True to show symbols
app.api.ControlCharacters = True
print("ControlCharacters set to True. Control characters will display as symbols.")

# Set ControlCharacters to False to render normally
app.api.ControlCharacters = False
print("ControlCharacters set to False. Control characters will render functionally.")

# Verify the change by getting the setting again
updated_setting = app.api.ControlCharacters
print(f"Updated ControlCharacters setting: {updated_setting}")

How to use Application.ConstrainNumeric in the xlwings API way

The ConstrainNumeric member of the Excel Application object is a property that controls whether Excel restricts numeric entry to a specific set of characters. This setting is particularly useful in environments where data entry must be standardized, such as when using numeric keypads or in locales with specific decimal and thousands separators. When enabled, it limits the characters that can be typed into cells to digits (0-9), the decimal point (which may vary by locale), the minus sign (-), and the slash (/) for fractions. This helps prevent accidental input of non-numeric characters, ensuring data integrity in worksheets that require pure numeric values. In xlwings, this property can be accessed and modified to automate the configuration of Excel’s behavior during data entry tasks, making it valuable for scripting scenarios where consistent numeric input is critical.

In terms of syntax, the ConstrainNumeric property is a Boolean type. It can be set to True to enforce numeric constraints or False to disable them. The xlwings API provides a straightforward way to interact with this property through the Application object. The general syntax is:

app.constrain_numeric

Here, app refers to an instance of the xlwings App class, which represents the Excel application. The property is read/write, meaning you can both retrieve its current value and assign a new one. For example, to enable numeric constraints, you would set app.constrain_numeric = True. Conversely, to check the current setting, you can read it with current_setting = app.constrain_numeric. Note that in xlwings, property names are typically in snake_case to align with Python conventions, even though the original VBA property is in PascalCase (e.g., ConstrainNumeric in VBA becomes constrain_numeric in xlwings).

To illustrate the usage, consider the following xlwings code examples. First, you might want to ensure numeric constraints are active before performing data entry operations. This can be done by setting the property at the start of a script:

import xlwings as xw

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

# Enable ConstrainNumeric to restrict input to numeric characters
app.constrain_numeric = True

print("Numeric constraints are now enabled.")

In a more dynamic scenario, you might toggle the setting based on user input or specific conditions. For instance, if you are automating a workbook that requires temporary relaxation of numeric constraints for text entry, you could disable and re-enable it as needed:

import xlwings as xw

app = xw.apps.active

# Disable numeric constraints to allow non-numeric input
app.constrain_numeric = False
print("Numeric constraints disabled. You can now enter text or symbols.")

# Perform some operations that require non-numeric input
# ...

# Re-enable numeric constraints after the operations
app.constrain_numeric = True
print("Numeric constraints re-enabled.")

Additionally, you can retrieve the current setting to log or make decisions in your script. This is useful for ensuring that the Excel environment is configured as expected before proceeding with data processing:

import xlwings as xw

app = xw.apps.active

# Check the current state of ConstrainNumeric
if app.constrain_numeric:
    print("Numeric entry is currently constrained to digits, decimal, minus, and slash.")
else:
    print("Numeric entry is not constrained; any characters can be input.")