Archive

How to use Application.CalculationVersion in the xlwings API way

The Application.CalculationVersion property in Excel is a read-only property that returns a Long value representing the version of the calculation engine used by Excel. This value is primarily used internally by Excel to track changes in calculation logic, such as after updates to functions or calculation methods. It can be useful for advanced troubleshooting, auditing, or when you need to ensure that a workbook’s calculations are consistent with a specific version of Excel’s calculation engine. In xlwings, you can access this property through the Application object.

Syntax in xlwings:

app.calculation_version
  • app: This is an instance of the xlwings App class, representing the Excel application. You typically obtain it by app = xw.apps.active or by creating a new instance.
  • calculation_version: This property returns an integer (Long) that encodes the calculation version. The value is composed of two parts: the major version (higher 16 bits) and the minor version (lower 16 bits). For example, a value of 196617 might correspond to version 3.9 (where 3 is the major part and 9 is the minor part, but exact mapping depends on Excel’s internal use).

Example Usage:
Here are a few code examples demonstrating how to use calculation_version with xlwings:

  1. Retrieving the Calculation Version:
    This example gets the calculation version from the active Excel application and prints it as a decimal number and as separate major/minor components using bitwise operations.
import xlwings as xw

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

# Get the calculation version
version = app.calculation_version
print(f"Calculation Version (decimal): {version}")

# Extract major and minor parts (higher 16 bits and lower 16 bits)
major_version = (version >> 16) & 0xFFFF
minor_version = version & 0xFFFF
print(f"Major Version: {major_version}, Minor Version: {minor_version}")
  1. Comparing Calculation Versions:
    You can compare the calculation version to a known value to check for compatibility or changes. For instance, you might want to verify if the version matches a specific release.
import xlwings as xw

app = xw.apps.active
current_version = app.calculation_version
target_version = 196617 # Example target version, adjust based on your needs

if current_version == target_version:
    print("Calculation engine is up-to-date with the target version.")
else:
    print(f"Calculation version differs. Current: {current_version}, Target: {target_version}")
  1. Logging Calculation Version for Auditing:
    In scenarios where you need to audit workbook calculations, you can log the calculation version along with other details to ensure reproducibility.
import xlwings as xw
import datetime

app = xw.apps.active
version = app.calculation_version
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Log to a file or print
log_entry = f"{timestamp} - Calculation Version: {version}\n"
with open("calculation_log.txt", "a") as log_file:
log_file.write(log_entry)
print("Calculation version logged successfully.")

Notes:

  • The exact meaning of the version number is not publicly documented by Microsoft and may change with Excel updates. It is generally used for internal tracking, so rely on it cautiously.
  • This property is available in Excel 2007 and later versions. In xlwings, ensure you have a compatible Excel installation.
  • Since calculation_version is read-only, you cannot set it directly; it reflects the current state of Excel’s calculation engine.

How to use Application.CalculationState in the xlwings API way

The CalculationState property of the Application object in Excel’s object model is accessible through the xlwings library, providing insight into the current calculation status of Excel. This property is particularly useful when automating tasks that depend on whether Excel is actively calculating formulas, has completed calculations, or is in a state where calculations are pending. By monitoring the CalculationState, developers can write more robust and efficient automation scripts that wait for calculations to finish before proceeding, thereby avoiding errors or incorrect data processing due to incomplete calculations.

Functionality:
The CalculationState property returns an integer value indicating the calculation state of Excel. It helps determine if Excel is busy calculating, done, or in another calculation-related state. This is essential in scenarios where subsequent operations, such as reading calculated cell values or saving workbooks, should only occur after all formulas have been recalculated. In xlwings, this property is accessed via the Application object, allowing Python scripts to interact with Excel’s calculation engine programmatically.

Syntax:
In xlwings, the CalculationState property is called on the app object, which represents the Excel application. The syntax is straightforward:

state = app.api.CalculationState

Here, app is an instance of the xlwings App class (e.g., created with app = xw.App() or xw.apps.active), and .api provides direct access to the underlying Excel object model. The CalculationState property does not take any parameters and returns an integer. The return values correspond to specific states, as defined in the Excel object model. Commonly used values include:

  • -4135 (or xlwings.constants.CalculationState.xlDone): Indicates that calculations are complete.
  • -4134 (or xlwings.constants.CalculationState.xlCalculating): Indicates that calculations are in progress.
  • -4133 (or xlwings.constants.CalculationState.xlPending): Indicates that calculations are pending, meaning some formulas need to be recalculated but Excel hasn’t started yet.

For clarity, xlwings provides constants in the xlwings.constants module, though they are not always required if using the raw integer values. Developers can refer to the Excel VBA documentation for a full list, but these three states are the most relevant for typical automation tasks.

Examples:
Below are practical xlwings API code examples demonstrating how to use the CalculationState property in Python scripts.

  1. Checking if Excel is currently calculating:
    This example waits for Excel to finish all calculations before proceeding, which is useful when working with workbooks that have complex formulas.
import xlwings as xw
import time

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

# Perform an action that triggers calculation, e.g., changing a cell value
wb = app.books.active
wb.sheets[0].range("A1").value = 10 # This might trigger recalculation

# Wait until calculations are complete
while app.api.CalculationState == -4134: # xlCalculating
time.sleep(0.1) # Pause briefly to avoid high CPU usage
print("Calculations finished. Safe to proceed.")
  1. Monitoring calculation state during a long operation:
    In this example, the script logs the calculation state while a large dataset is being processed, helping to debug or optimize performance.
import xlwings as xw

app = xw.App(visible=True) # Start a new Excel instance
wb = app.books.add()
sheet = wb.sheets[0]

# Fill a range with formulas to simulate a heavy calculation load
for i in range(1, 101):
    sheet.range(f"A{i}").formula = f"=RAND()*{i}"

# Force a full calculation
app.api.Calculate()

# Check and print the calculation state
state = app.api.CalculationState
if state == -4134:
    print("Excel is currently calculating formulas.")
elif state == -4135:
    print("Excel has finished all calculations.")
elif state == -4133:
    print("Calculations are pending.")
else:
    print(f"Unknown calculation state: {state}")

# Clean up
wb.close()
app.quit()
  1. Using constants for better readability:
    While xlwings doesn’t have built-in enums for all Excel constants, developers can define their own or use the ones available. This example shows how to use constants to make the code more maintainable.
import xlwings as xw

# Define constants based on Excel's object model (or import from xlwings.constants if available)
xlCalculating = -4134
xlDone = -4135
xlPending = -4133

app = xw.apps.active
state = app.api.CalculationState

if state == xlCalculating:
print("Wait for calculations to complete.")
elif state == xlDone:
print("Proceed with data extraction.")
else:
print("Check for pending calculations.")

How to use Application.CalculationInterruptKey in the xlwings API way

The Application.CalculationInterruptKey property in Excel is a member that allows developers to control which key can be used to interrupt a long calculation in Excel. This is particularly useful when running complex or lengthy calculations where you might want to provide a way to stop the process without forcing Excel to become unresponsive. In xlwings, this property can be accessed and modified through the Application object, providing a programmatic way to manage calculation interruptions in automated Excel tasks.

Functionality:
The CalculationInterruptKey property determines the key that, when pressed during a calculation, will interrupt the process. It helps in creating more user-friendly or controlled environments by specifying whether interruptions are allowed and which key triggers them. This can prevent accidental interruptions or allow for deliberate stops in scenarios like data processing macros.

Syntax in xlwings:
In xlwings, you can access this property using the api property of the App or Book objects to reach the underlying Excel Application object. The syntax is as follows:

app = xw.apps.active # Get the active Excel application
interrupt_key = app.api.CalculationInterruptKey

To set the property, assign a value from the XlCalculationInterruptKey enumeration. The available options are:

  • xlAnyKey (1): Any key press will interrupt the calculation.
  • xlEscKey (2): Only the Esc key will interrupt the calculation.
  • xlNoKey (3): No key will interrupt the calculation; this disables interruptions.

Parameters and Values:
The property accepts integer values corresponding to the enumeration. In xlwings, you can use the constants directly if imported, but typically, you can use the integer values for simplicity. For example:

  • Use 1 for xlAnyKey.
  • Use 2 for xlEscKey.
  • Use 3 for xlNoKey.

Example Usage:
Here is a code example demonstrating how to set and retrieve the CalculationInterruptKey property using xlwings:

import xlwings as xw

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

# Get the current interrupt key setting
current_key = app.api.CalculationInterruptKey
print(f"Current interrupt key setting: {current_key}") # Output might be 2 for xlEscKey

# Set the interrupt key to xlAnyKey (any key press interrupts)
app.api.CalculationInterruptKey = 1 # Equivalent to xlAnyKey
print("Interrupt key set to xlAnyKey.")

# Perform a long calculation (e.g., a loop that simulates work)
# In a real scenario, this could be a heavy Excel calculation.
try:
    # Simulate a calculation that might be interrupted
    for i in range(1000000):
        # Some calculation code here
        if i % 100000 == 0:
            print(f"Processing... {i}")
except KeyboardInterrupt:
    print("Calculation was interrupted by user.")

# Reset to xlEscKey for standard behavior
app.api.CalculationInterruptKey = 2
print("Interrupt key reset to xlEscKey.")

How to use Application.Calculation in the xlwings API way

The Application.Calculation property in Excel is a crucial setting that determines how formulas are recalculated within a workbook. In xlwings, this property allows you to control the calculation mode programmatically, which is essential for optimizing performance, especially when dealing with large or complex spreadsheets that involve numerous formulas and dependencies.

Functionality
This property controls the Excel calculation engine’s mode. You can set it to force automatic recalculation, manual recalculation, or a semi-automatic mode. This is particularly useful when you are writing data to many cells via xlwings and want to prevent Excel from recalculating after each write operation, which can significantly slow down execution. By setting calculation to manual, performing all data updates, and then setting it back to automatic (or triggering a manual calculation), you can drastically improve the performance of your scripts.

Syntax and Parameters
In xlwings, you access this property through the app object, which represents the Excel Application. The syntax is straightforward:
app.calculation
This property is both gettable and settable. When setting it, you assign one of the following constants, which are available directly in xlwings:

Constant (from xlwings.constants)ValueDescription
xlwings.constants.Calculation.xlCalculationAutomatic-4105Excel controls recalculation.
xlwings.constants.Calculation.xlCalculationManual-4135Recalculation only occurs when explicitly requested (e.g., by pressing F9).
xlwings.constants.Calculation.xlCalculationSemiautomatic2Recalculation is automatic except for data tables.

You can also use the raw numeric values, but using the named constants is recommended for better code readability.

Code Examples
Here are practical examples of using the app.calculation property with xlwings:

  1. Checking the Current Calculation Mode:
import xlwings as xw
app = xw.apps.active # Get the active Excel application
current_mode = app.calculation
print(f"Current calculation mode is: {current_mode}")
  1. Setting Calculation to Manual for Performance:
    This is a common pattern for batch operations.
import xlwings as xw
from xlwings.constants import Calculation

app = xw.apps.active
original_mode = app.calculation # Save the original state

# Set to manual to prevent recalculations during data writes
app.calculation = Calculation.xlCalculationManual

# Perform your data operations (e.g., writing to many cells)
wb = app.books.active
sht = wb.sheets[0]
for row in range(2, 1002):
    sht.range(f'A{row}').value = row * 10
    # Without manual calculation, Excel would recalculate here 1000 times!

# After data is written, trigger a single full calculation
wb.app.calculate() # Equivalent to pressing F9 in Excel

# Restore the original calculation mode
app.calculation = original_mode
  1. Setting Calculation to Automatic:
import xlwings as xw
from xlwings.constants import Calculation

app = xw.apps.active
app.calculation = Calculation.xlCalculationAutomatic
print("Calculation set to Automatic.")

How to use Application.CalculateBeforeSave in the xlwings API way

The Application.CalculateBeforeSave property in Excel’s object model controls whether calculation occurs automatically before a workbook is saved. This setting is particularly useful in large or complex workbooks where manual calculation mode is enabled to improve performance during data entry or manipulation. By setting CalculateBeforeSave to True, you ensure all formulas are recalculated with the latest data upon saving, preventing outdated results. When set to False, Excel skips this recalculation step, which can speed up the saving process but may leave formulas unupdated.

In xlwings, you can access this property through the Application object. The syntax is straightforward: app.calculate_before_save, where app represents the xlwings App instance. This property accepts a Boolean value: True enables pre-save calculation, and False disables it. It’s important to note that this is a global setting applied to the Excel application instance, affecting all open workbooks managed by that instance. You can both retrieve the current setting and modify it as needed.

For example, to check the current CalculateBeforeSave setting using xlwings, you can use the following code:

import xlwings as xw

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

# Get the current CalculateBeforeSave value
current_setting = app.calculate_before_save
print(f"CalculateBeforeSave is currently set to: {current_setting}")

To change the setting, assign a new Boolean value. The code below disables calculation before saving, which might be beneficial for performance in large workbooks:

import xlwings as xw

app = xlwings.apps.active
# Disable calculation before saving
app.calculate_before_save = False
print("CalculateBeforeSave has been disabled.")

If you need to enable it again to ensure data accuracy, simply set it to True:

app.calculate_before_save = True
print("CalculateBeforeSave has been enabled.")

A practical use case involves toggling this property during automated processes. For instance, if you’re running a script that makes numerous changes and saves intermittently, disabling CalculateBeforeSave can reduce overhead. After completing all updates, you can re-enable it and force a manual recalculation before the final save:

import xlwings as xw

app = xw.apps.active
workbook = app.books.active

# Disable calculation to speed up intermediate saves
app.calculate_before_save = False
# Perform data manipulations...
workbook.save('temp_save.xlsx')

# Re-enable calculation and recalculate before final save
app.calculate_before_save = True
workbook.calculate()
workbook.save('final_save.xlsx')

How to use Application.Build in the xlwings API way

The Application.Build property in Excel’s object model represents the build number of the Excel application. This read-only property returns a Long value that corresponds to the specific compilation version of Excel. It is particularly useful for developers who need to implement version-specific logic or ensure compatibility across different builds of Excel, as it provides a more granular identifier than the major version number alone.

In xlwings, the Application object is accessed via the app object when you have an instance of an Excel application. The Build property can be retrieved directly as an attribute. The syntax is straightforward: after establishing a connection to Excel, you simply call .build on the app object. There are no parameters required for this property.

Syntax:

app.build

This returns an integer representing the build number. For example, in Excel 365, this might be a number like 16.0.xxxxx, but note that Build returns only the numeric build part.

Example Usage:
Consider a scenario where you are automating a report and need to check if the Excel build is compatible with a certain feature. You can retrieve the build number and use it in conditional statements. Below is a code example using xlwings:

import xlwings as xw

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

# Get the build number
build_number = app.build

# Output the build number
print(f"Excel Build Number: {build_number}")

# Example: Check for a specific build range (e.g., builds after 15000)
if build_number > 15000:
    print("This build supports advanced features.")
else:
    print("Consider updating Excel for full functionality.")

# Close the app if it was created in this script (optional)
if not xw.apps.active:
    app.quit()

How to use Application.AutoRecover in the xlwings API way

The AutoRecover member of the Application object in Excel’s object model is a critical feature for data integrity and user productivity. In xlwings, this functionality is accessible through the api property, allowing Python scripts to interact with Excel’s native automation interface. The AutoRecover object itself provides properties that enable developers to control and query Excel’s automatic file recovery settings programmatically. This is particularly useful in automation scripts where workbook stability and recovery options need to be managed dynamically, such as in long-running data processing tasks or when deploying Excel-based solutions in environments with intermittent connectivity.

In xlwings, the syntax to access the AutoRecover member is straightforward, as it is a property of the Application object. The typical approach involves obtaining the Excel application instance from a workbook or creating one, then accessing the property.

The syntax is:

app.api.AutoRecover

where app is the xlwings App instance representing the Excel application. The AutoRecover object does not have methods in the traditional sense but exposes several key properties that can be read or set. These properties include Path, which specifies the directory where AutoRecover files are saved, and Time, which sets the time interval in minutes for automatic saving of recovery information. Both properties are of type Variant in Excel’s object model and can be accessed as attributes in xlwings.

For example, app.api.AutoRecover.Path returns a string representing the path, and app.api.AutoRecover.Time returns an integer. Setting these properties is equally simple: assign a string to Path or an integer to Time within valid ranges (e.g., Time must be between 1 and 120 minutes). It’s important to note that changes to these properties apply globally to the Excel instance and may affect other open workbooks.

To illustrate the usage, consider a scenario where an automation script needs to ensure that AutoRecover is configured optimally before performing intensive operations. The following xlwings code examples demonstrate how to interact with the AutoRecover member. First, import xlwings and start an Excel application:

import xlwings as xw;

app = xw.App(visible=False)

To retrieve the current AutoRecover path, use current_path = app.api.AutoRecover.Path; print(current_path). To set a new path, such as a dedicated network drive for recovery files, execute app.api.AutoRecover.Path = r'C:\AutoRecoverBackup'. For the time interval, fetch the current setting with current_time = app.api.AutoRecover.Time; print(current_time), and update it to 10 minutes with app.api.AutoRecover.Time = 10. After completing operations, it’s good practice to reset or close the application: app.quit(). These examples show how xlwings seamlessly bridges Python and Excel, enabling robust management of recovery settings to prevent data loss in automated workflows.

How to use Application.AutoPercentEntry in the xlwings API way

The AutoPercentEntry property of the Application object in Excel is a feature that controls the automatic conversion of decimal numbers into percentages when entered into cells. When this property is set to True, any decimal value (e.g., entering 0.15) typed into a cell will automatically be formatted as a percentage (15%). This can significantly streamline data entry in scenarios where percentage inputs are frequent, reducing the need for manual formatting. However, it’s important to note that this is a global application setting, meaning it affects all open workbooks and worksheets. Users should be cautious, as enabling it might inadvertently convert decimal data intended as other numeric types.

In the xlwings API, which provides a powerful bridge between Python and Excel, you access this property through the app object, which represents the Excel application. The property is available for both getting its current state and setting it to a new value.

Syntax in xlwings:

app.api.AutoPercentEntry
  • Get: current_state = app.api.AutoPercentEntry
  • Set: app.api.AutoPercentEntry = new_value
  • Parameters: This property does not take parameters. It is a Boolean property where True enables automatic percentage entry and False disables it.

Code Examples:

  1. Checking the Current Setting:
import xlwings as xw
app = xw.apps.active # Get the active Excel application
is_enabled = app.api.AutoPercentEntry
print(f"AutoPercentEntry is currently set to: {is_enabled}")
  1. Enabling AutoPercentEntry:
import xlwings as xw
app = xw.apps.active
app.api.AutoPercentEntry = True
print("AutoPercentEntry has been enabled.")
# Now, entering 0.2 in a cell will display as 20%.
  1. Disabling AutoPercentEntry:
import xlwings as xw
app = xw.apps.active
app.api.AutoPercentEntry = False
print("AutoPercentEntry has been disabled.")
# Decimal entries will now remain as decimals unless manually formatted.
  1. Practical Workflow Example: This script toggles the setting, enters a test value, and then restores the original state.
import xlwings as xw
app = xw.apps.active
original_setting = app.api.AutoPercentEntry

# Enable for a task
app.api.AutoPercentEntry = True
wb = app.books.active
ws = wb.sheets[0]
ws.range('A1').value = 0.35 # Will appear as 35% in Excel
print("Test value 0.35 entered into A1 with AutoPercentEntry ON.")

# Restore original setting
app.api.AutoPercentEntry = original_setting
print(f"AutoPercentEntry restored to {original_setting}.")

How to use Application.AutomationSecurity in the xlwings API way

The AutomationSecurity property of the Application object in Excel is a crucial setting for controlling macro security when automating Excel through external applications like Python using the xlwings library. It determines the security level that Excel uses when opening files programmatically, which can affect whether macros are enabled or disabled automatically. This property is particularly important in scenarios where automation scripts need to ensure consistent security behavior, especially in environments with varying macro settings. By setting AutomationSecurity, developers can programmatically override the default security settings of Excel, providing more control over macro execution during automated processes. This helps in maintaining security protocols while allowing necessary macros to run in controlled automation tasks.

In xlwings, the AutomationSecurity property is accessed through the app object, which represents the Excel application. The syntax for setting or getting this property is straightforward, as it corresponds directly to the Excel Object Model. The property accepts integer values that correspond to specific security levels defined by Excel. The primary values are:

  • 1 (msoAutomationSecurityLow): This setting enables all macros to run without prompting. It is useful in trusted environments but poses security risks if used with untrusted files.
  • 2 (msoAutomationSecurityByUI): Excel uses the macro security level set in the user interface (via Trust Center settings). This is the default behavior when automation is initiated.
  • 3 (msoAutomationSecurityForceDisable): This setting disables all macros automatically, regardless of the file’s trust settings. It is the most secure option, preventing any macro execution.

To use this property in xlwings, you first need to instantiate an Excel application object. The property can be set before opening a workbook to influence how Excel handles macros in that file. For example, if you want to ensure macros are disabled during an automated data processing task, you can set AutomationSecurity to 3. Conversely, if you trust the source and need macros to run, set it to 1. It’s essential to note that changing this property affects all subsequent workbooks opened in that instance of Excel until it is changed again or the application is closed.

Here is a code example demonstrating the use of AutomationSecurity in xlwings:

import xlwings as xw

# Start a new Excel application instance
app = xw.App(visible=False) # Run Excel in the background

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

# Set AutomationSecurity to disable all macros (msoAutomationSecurityForceDisable)
app.api.AutomationSecurity = 3
print("AutomationSecurity set to disable all macros.")

# Open a workbook that contains macros
wb = app.books.open('example_with_macros.xlsx')

# Perform some operations, such as reading data
data = wb.sheets['Sheet1'].range('A1').value
print(f"Data from A1: {data}")

# Set AutomationSecurity back to use UI settings (msoAutomationSecurityByUI)
app.api.AutomationSecurity = 2
print("AutomationSecurity reset to UI default.")

# Close the workbook without saving
wb.close()

# Quit the Excel application
app.quit()

How to use Application.AutoFormatAsYouTypeReplaceHyperlinks in the xlwings API way

The AutoFormatAsYouTypeReplaceHyperlinks member of the Application object in Excel is a property that controls whether Excel automatically formats text that resembles a hyperlink address into a clickable hyperlink as you type. This is part of the “AutoFormat as you type” feature, which can help in quickly creating interactive documents by converting typed URLs or network paths into functional links without manual formatting. In xlwings, this property is accessible via the Application object’s API, allowing you to programmatically check or set this automation setting, which can be particularly useful in scripts that prepare or clean Excel workbooks for specific user interactions.

Syntax in xlwings:
In xlwings, you interact with this property through the app object, which represents the Excel Application. The property is exposed as a boolean attribute. The syntax is straightforward:

app.api.AutoFormatAsYouTypeReplaceHyperlinks

This property can be both read and written. When reading, it returns True if the feature is enabled, and False if disabled. When writing, you can set it to True to enable automatic hyperlink formatting, or False to disable it. There are no additional parameters or arguments for this property, as it is a simple toggle.

Example Usage with xlwings:
Below is a practical example demonstrating how to use the AutoFormatAsYouTypeReplaceHyperlinks property in a Python script with xlwings. This example checks the current setting, toggles it based on a condition, and then types some text to observe the effect (if Excel is visible). Note that changes to this setting may affect the user’s Excel session, so it’s often used in controlled environments or reset afterward.

import xlwings as xw

# Start or connect to an Excel application
app = xw.App(visible=True) # Set visible=True to see the typing effect
wb = app.books.add()

# Access the AutoFormatAsYouTypeReplaceHyperlinks property
current_setting = app.api.AutoFormatAsYouTypeReplaceHyperlinks
print(f"Current AutoFormatAsYouTypeReplaceHyperlinks setting: {current_setting}")

# Toggle the setting: enable if disabled, or disable if enabled
new_setting = not current_setting
app.api.AutoFormatAsYouTypeReplaceHyperlinks = new_setting
print(f"Setting changed to: {new_setting}")

# To see the effect, type a URL in a cell (requires Excel to be visible and active)
if app.visible:
    sheet = wb.sheets[0]
    sheet.range('A1').value = "Visit https://www.example.com for more info."
    # If enabled, Excel will format the URL as a hyperlink automatically as you type.
    # Note: In xlwings, setting cell value programmatically may not trigger the "as you type" feature,
    # as it simulates direct value insertion rather than keystroke-by-keystroke typing.
    # The feature primarily works during manual typing in the Excel interface.

    # Restore the original setting (optional, for user convenience)
    app.api.AutoFormatAsYouTypeReplaceHyperlinks = current_setting

# Save and close
wb.save('hyperlink_example.xlsx')
wb.close()
app.quit()

Important Notes:

  • The AutoFormatAsYouTypeReplaceHyperlinks property affects the entire Excel application session, not just a specific workbook. Changing it will influence all open workbooks and future typing actions.
  • In xlwings, when you set a cell’s value using .value, Excel may not apply the “as you type” formatting because it is not simulating real-time keystrokes. The feature is designed for manual entry in the Excel GUI. Therefore, toggling this property via xlwings is more about configuring the environment for user interaction rather than for programmatic data insertion.
  • This property is part of Excel’s application-level options, so it’s persistent across sessions if saved in the user’s settings, but xlwings changes are temporary for the current session unless explicitly saved via Excel’s options dialog.