Archive

How to use Range.AllocateChanges in the xlwings API way

The AllocateChanges member of the Range object in Excel is a method used within the context of shared workbooks that have change tracking enabled. Its primary function is to manually apply or resolve pending changes that have been tracked in the workbook. When multiple users edit a shared workbook, Excel can track changes, and these changes remain in a pending state until they are reviewed and either accepted or rejected. The AllocateChanges method allows a developer to programmatically process these tracked changes, applying them to the workbook. This is particularly useful for automating the reconciliation of edits in collaborative environments, ensuring that all modifications are properly integrated without manual intervention through the “Track Changes” dialog box.

In the Excel Object Model, this method is accessed via VBA as Range.AllocateChanges. However, when using the xlwings library in Python to interact with Excel, you do not call this method directly on a Range object through xlwings’ typical API. Instead, xlwings provides a bridge to the underlying COM object model. Therefore, to use AllocateChanges, you must access the raw Excel COM object that xlwings wraps. The syntax for this involves using the api property of an xlwings Range object to get the native Excel Range object, and then calling the method on it.

Syntax in xlwings:

range_obj.api.AllocateChanges

Where range_obj is an xlwings Range object (e.g., sheet.range('A1')). The AllocateChanges method does not take any parameters in its standard form. It simply applies all pending changes within the range. If the range is a single cell, Excel will apply changes for the entire sheet. It’s important to note that this method is only applicable when the workbook is shared and changes are being tracked. If these conditions are not met, calling the method may result in an error.

Example Usage:
Consider a scenario where you have a shared workbook with tracked changes, and you want to apply all pending changes in the range “B2:D10”. The following xlwings code demonstrates how to do this:

import xlwings as xw

# Connect to the active Excel instance and workbook
app = xw.apps.active
wb = app.books['SharedWorkbook.xlsx'] # Ensure this is a shared workbook

# Specify the worksheet and range
sheet = wb.sheets['Data']
target_range = sheet.range('B2:D10')

# Apply all pending changes in the specified range using the COM API
target_range.api.AllocateChanges

# Save the workbook to persist the changes
wb.save()

How to use Range.AdvancedFilter in the xlwings API way

The AdvancedFilter method of the Range object in Excel is a powerful tool for performing complex filtering operations, such as extracting unique records or filtering based on criteria ranges. In xlwings, this method can be accessed through the api property, which provides direct access to Excel’s underlying object model. This allows for sophisticated data manipulation directly from Python, leveraging Excel’s built-in capabilities for handling large datasets with custom criteria.

Functionality:
The AdvancedFilter method is primarily used to filter a range of data in place or to copy filtered results to another location. It supports two main actions: filtering in place (similar to using Excel’s Advanced Filter dialog without copying) and copying unique records to a specified destination. It can also use criteria ranges to define complex filtering conditions, such as multiple criteria across columns. This is useful for tasks like deduplication, conditional data extraction, and applying multi-condition filters that go beyond standard AutoFilter capabilities.

Syntax in xlwings:
In xlwings, the method is called via the api property on a Range object. The basic syntax is:

range_object.api.AdvancedFilter(Action, CriteriaRange, CopyToRange, Unique)
  • Action: Specifies whether to filter the list in place or copy the results. It is a constant from the XlFilterAction enumeration:
  • xlFilterInPlace (value 1): Filters the range without moving it.
  • xlFilterCopy (value 2): Copies filtered results to another location.
  • CriteriaRange: A Range object representing the criteria range. This is optional; if omitted, no criteria are applied. The criteria range should include column headers and conditions (e.g., using operators like “>”, “<“, or specific values). It can be set to None if not used.
  • CopyToRange: A Range object specifying where to copy the results if Action is xlFilterCopy. This is required only for copy actions; otherwise, it can be omitted or set to None. It should include the destination’s top-left cell or a range with column headers.
  • Unique: A boolean value (True or False) that indicates whether to extract only unique records. If True, duplicate rows are removed from the output. Default is False.

Example Usage:
Suppose we have an Excel workbook with data in the range A1:C10, where column A is “Name”, B is “Sales”, and C is “Region”. We want to filter for sales greater than 1000 in the “East” region and copy unique records to a new location. First, we define a criteria range in E1:F2 (with headers “Sales” and “Region” and conditions “>1000” and “East”). Here’s the xlwings code:

import xlwings as xw

# Connect to the active workbook and sheet
wb = xw.books.active
sheet = wb.sheets['Sheet1']

# Define the data range and criteria range
data_range = sheet.range('A1:C10')
criteria_range = sheet.range('E1:F2')
copy_dest = sheet.range('H1') # Starting cell for copied results

# Apply Advanced Filter to copy unique records based on criteria
data_range.api.AdvancedFilter(
Action=2, # xlFilterCopy
CriteriaRange=criteria_range,
CopyToRange=copy_dest,
Unique=True
)

How to use Range.AddCommentThreaded in the xlwings API way

The AddCommentThreaded member of the Range object in the Excel object model enables the creation of a modern, threaded comment (introduced in Microsoft 365) within a specified cell or range. Unlike traditional notes or legacy comments, threaded comments support conversational replies, mentions (@), and are stored separately, making them ideal for collaborative discussions directly within a spreadsheet. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model, allowing precise control over comment creation and properties.

Syntax in xlwings:
range.api.AddCommentThreaded(Text)

  • range: An xlwings Range object representing the target cell or range (e.g., sheet.range('A1')).
  • .api: Accesses the native Excel VBA object model.
  • Text (optional): A string specifying the initial text of the comment thread. If omitted, an empty comment is created.

This method returns a CommentThreaded object, which can be further manipulated—for instance, to add replies, edit text, or resolve the thread. Key properties of the returned object include Text (for the initial comment), Author (the creator’s name), and Replies (a collection of reply objects).

Example Usage with xlwings:

  1. Creating a Basic Threaded Comment:
import xlwings as xw

# Connect to the active workbook and sheet
wb = xw.books.active
sheet = wb.sheets['Sheet1']

# Add a threaded comment to cell B5
target_cell = sheet.range('B5')
new_thread = target_cell.api.AddCommentThreaded("Initial review: Please verify these figures by EOD.")
  1. Adding a Comment with a Mention and Retrieving Properties:
# Add a comment with a mention (using the @ symbol to tag a collaborator)
thread = sheet.range('C10').api.AddCommentThreaded("@Alex, can you provide the Q3 data here?")

# Access properties of the new threaded comment
print(f"Author: {thread.Author}")
print(f"Text: {thread.Text}")
print(f"Date/Time: {thread.Date}")

# Add a reply to the thread
thread.Replies.Add("I'll upload the file by 3 PM today.")
  1. Handling an Existing Comment Thread:
    If a cell already contains a threaded comment, using AddCommentThreaded will raise an error. To avoid this, check for existing comments first:
cell = sheet.range('D2')
if cell.api.CommentThreaded is None:
    cell.api.AddCommentThreaded("New discussion thread.")
else:
    print("A threaded comment already exists in this cell.")

How to use Range.AddComment in the xlwings API way

The AddComment method in xlwings is a powerful feature that allows developers to programmatically add comment threads (formerly known as “notes”) to specific cells within an Excel worksheet. This functionality is essential for adding annotations, explanations, or instructions directly to cell data, enhancing the clarity and collaborative potential of a spreadsheet. In modern Excel, comments are interactive threads, and xlwings provides a straightforward API to manage them.

Syntax and Parameters

In xlwings, the AddComment method is accessed through a Range object. The basic syntax is:

range_object.add_comment(text)
  • range_object: This is an xlwings Range object, representing the cell or range of cells to which you want to attach the comment. The comment will be anchored to the first cell in this range.
  • text (str): The required string parameter that contains the text you want to display in the comment thread. This is the body of the comment.

The method returns an xlwings Comment object, which provides properties and methods to further manipulate the comment (e.g., comment.text to get or set the text later, comment.delete() to remove it).

Key Behavior and Notes

  • If the target cell already has a comment, using add_comment will raise a ValueError. To safely set or update a comment, you should first check for and delete any existing comment using range_object.comment and comment.delete().
  • The comment is created as a thread. In Excel’s UI, it will appear with the current application user’s name.
  • xlwings interacts with the Excel Object Model, and add_comment maps directly to the Range.AddComment method in the VBA object library.

Code Examples

Here are practical examples demonstrating the use of add_comment:

  1. Adding a Simple Comment to a Cell:
    This example adds an explanatory comment to cell B5.
import xlwings as xw
# Connect to the active workbook and sheet
wb = xw.books.active
sht = wb.sheets.active
# Add a comment to cell B5
comment_obj = sht.range("B5").add_comment("Please verify this figure with the Q3 report.")
print(f"Comment added. Its text is: {comment_obj.text}")
  1. Safely Adding or Replacing a Comment:
    This pattern checks for an existing comment and replaces it, preventing errors.
import xlwings as xw
wb = xw.books.active
target_cell = wb.sheets["Sheet1"].range("C10")
# Check for and delete an existing comment
if target_cell.comment:
    target_cell.comment.delete()
    print("Old comment deleted.")
    # Add the new comment
    target_cell.add_comment("Updated forecast as of 2024-05-17.")
  1. Adding Comments Based on Cell Values:
    Automate comment insertion by looping through a data range.
import xlwings as xw
wb = xw.books.active
sht = wb.sheets["Data"]
# Assume column A has values, add a comment in column B for negative values
last_row = sht.range("A1").end("down").row
for i in range(1, last_row + 1):
    value = sht.range(f"A{i}").value
    if isinstance(value, (int, float)) and value < 0:
        # Clear any existing comment before adding
        if sht.range(f"B{i}").comment:
            sht.range(f"B{i}").comment.delete()
            sht.range(f"B{i}").add_comment(f"Negative value. Check source transaction.")

How to use Range.Activate in the xlwings API way

The Activate member of the Range object in the Excel object model is a method that makes a specific cell or range the active selection within a worksheet, bringing it into focus. In xlwings, this functionality is directly accessible, allowing for programmatic navigation and interaction with Excel workbooks. Activating a range is particularly useful when you need to visually highlight a cell for the user, prepare for subsequent operations like data entry or formatting that depend on the active cell, or ensure a specific area is in view during macro execution. While excessive use of Activate can slow down scripts, it remains a valuable tool for creating user-friendly and guided Excel automation processes.

In xlwings, the Activate method is called on a Range object. The syntax is straightforward, as the method does not take any parameters.

Syntax:
range_object.activate()

  • range_object: This is an instance of the xlwings Range class, representing a single cell or a contiguous block of cells (e.g., A1, B2:D5).
  • The activate() method requires no arguments. When called, it selects and activates the top-left cell of the specified range in the associated Excel application instance, making it the active cell.

Code Examples:

  1. Activating a Single Cell:
    This code opens a workbook, makes cell C10 on the first sheet the active cell, and brings the Excel window to the foreground.
import xlwings as xw
# Connect to an open workbook or open a new one
app = xw.App(visible=True)
book = app.books.open('example.xlsx')
sheet = book.sheets[0]

# Activate cell C10
sheet.range('C10').activate()

# Optional: Force Excel window to the front
app.api.ActiveWindow.Activate()
  1. Activating a Range and Performing an Action:
    This example activates a larger range (A1:E1) and then applies a bold font format to it. Activating the range first ensures it is selected before the format is applied, which can be helpful for visual feedback.
import xlwings as xw
with xw.App(visible=False) as app:
wb = app.books.add()
ws = wb.sheets['Sheet1']
target_range = ws.range('A1:E1')

# Activate the range and then format it
target_range.activate()
target_range.api.Font.Bold = True

wb.save('activated_range.xlsx')
  1. Using Activate with the Current Region:
    This script finds the current region around cell A1 (the contiguous data block) and activates the cell immediately to the right of the last used cell in the first row. This pattern is common for navigating to the end of a data table.
import xlwings as xw
app = xw.App(visible=True)
book = app.books.open('data_source.xlsx')
sheet = book.sheets['SalesData']

# Get the current region from A1
data_region = sheet.range('A1').current_region

# Activate the cell in the first row, one column past the last column of the region
last_col = data_region.last_cell.column
sheet.range(1, last_col + 1).activate() # Activates the cell in row 1, next column

book.save()
app.quit()

How to use Worksheet.VPageBreaks in the xlwings API way

The VPageBreaks member of a Worksheet object in Excel’s object model represents the collection of vertical page breaks within the sheet. In xlwings, this collection is accessible via the api property, allowing you to programmatically manage where pages are divided when printing. This is particularly useful for creating custom print layouts, ensuring that data is segmented logically across multiple pages without manual adjustment. The VPageBreaks collection contains VPageBreak objects, each representing a single vertical page break.

Syntax in xlwings:
To access the VPageBreaks collection in xlwings, use the following pattern:
worksheet.api.VPageBreaks
Here, worksheet is an xlwings Sheet object. The VPageBreaks collection supports methods and properties for adding, counting, and retrieving vertical page breaks. Key members include:

  • Add(Before): Adds a new vertical page break. The Before parameter is a required argument of type Object, specifying the column to the left of which the break is inserted. In xlwings, you typically pass an Excel Range object representing the column (e.g., worksheet.range("C1").api to insert a break before column C).
  • Count: A read-only property that returns the number of vertical page breaks in the collection (integer).
  • Item(Index): Returns a single VPageBreak object from the collection. The Index parameter is the break number, starting from 1 for the leftmost break.

Example Usage with xlwings:
Below are code examples demonstrating how to use VPageBreaks in xlwings for common tasks. Ensure you have an Excel workbook open and referenced via xlwings.

  1. Adding a Vertical Page Break:
    This example inserts a vertical page break before column D (i.e., between columns C and D) on the active sheet.
import xlwings as xw
wb = xw.Book.active # Assume an active workbook
ws = wb.sheets.active
# Add a vertical page break before column D
ws.api.VPageBreaks.Add(Before=ws.range("D1").api)
print("Vertical page break added before column D.")
  1. Counting Vertical Page Breaks:
    This snippet counts and displays the total vertical page breaks in the worksheet.
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets.active
break_count = ws.api.VPageBreaks.Count
print(f"Number of vertical page breaks: {break_count}")
  1. Iterating Through and Removing Vertical Page Breaks:
    This example loops through all vertical page breaks and removes each one, clearing manual break settings.
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets.active
vpage_breaks = ws.api.VPageBreaks
# Iterate in reverse to avoid index issues when deleting
for i in range(vpage_breaks.Count, 0, -1):
    vbreak = vpage_breaks.Item(i)
    vbreak.Delete() # Remove the page break
    print("All vertical page breaks have been removed.")
  1. Accessing a Specific Page Break’s Location:
    This code retrieves the leftmost vertical page break and prints its column location.
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets.active
if ws.api.VPageBreaks.Count > 0:
    first_vbreak = ws.api.VPageBreaks.Item(1)
    # The Location property returns a Range object for the column to the left of the break
    break_location = first_vbreak.Location.Column
    print(f"The first vertical page break is before column: {break_location}")
else:
    print("No vertical page breaks exist.")

How to use Worksheet.Visible in the xlwings API way

The Visible property of a Worksheet object in Excel, when accessed through the xlwings API, allows you to control the visibility state of a worksheet. This is useful for temporarily hiding sheets from view without deleting them, often to simplify the user interface or to conceal intermediate calculation sheets. A worksheet can be set to be fully visible, completely hidden, or very hidden—the last state means the sheet is hidden and cannot be made visible through the standard Excel user interface (like the “Unhide” dialog), providing an additional layer of concealment.

Syntax:
In xlwings, you interact with the Visible property through a Sheet object (which corresponds to a Worksheet in Excel). The property can be both retrieved and set.

  • Getting the current visibility state:
    sheet.visible
    This returns a string indicating the current state: 'visible', 'hidden', or 'very_hidden'.
  • Setting the visibility state:
    sheet.visible = state
    Here, state is a string that must be one of the following accepted values:
ValueDescription
'visible'Makes the worksheet appear normally in the workbook.
'hidden'Hides the worksheet, but it can be unhidden via Excel’s “Format” > “Hide & Unhide” > “Unhide Sheet” menu.
'very_hidden'Hides the worksheet and removes it from the “Unhide Sheet” dialog. It can only be made visible again programmatically (e.g., via VBA or xlwings).

Code Examples:

  1. Hiding and Unhiding a Sheet:
import xlwings as xw

# Connect to the active workbook
wb = xw.books.active

# Get a reference to a specific sheet
data_sheet = wb.sheets['Sheet1']

# Hide the sheet
data_sheet.visible = 'hidden'
print(f"Sheet1 is now: {data_sheet.visible}") # Output: hidden

# Later, make it visible again
data_sheet.visible = 'visible'
  1. Making a Sheet Very Hidden:
import xlwings as xw

wb = xw.books.active
calc_sheet = wb.sheets['Calculations']

# Hide it so it doesn't appear in the Unhide dialog
calc_sheet.visible = 'very_hidden'

# Check its status
print(calc_sheet.visible) # Output: very_hidden
# To restore it, you must use xlwings again:
# calc_sheet.visible = 'visible'
  1. Iterating Through Sheets and Hiding Based on Name:
import xlwings as xw

wb = xw.books.active

for sheet in wb.sheets:
# Hide all sheets with 'Temp' in their name
if 'Temp' in sheet.name:
    sheet.visible = 'hidden'
    print(f"Hid sheet: {sheet.name}")
  1. Checking if a Sheet is Visible Before Performing an Action:
import xlwings as xw

wb = xw.books.active
report_sheet = wb.sheets['FinalReport']

# Only write data if the sheet is currently visible
if report_sheet.visible == 'visible':
    report_sheet.range('A1').value = 'Report Generated'
else:
    print("Cannot write to a hidden report sheet.")

How to use Worksheet.UsedRange in the xlwings API way

The UsedRange property of a Worksheet object in Excel is a powerful feature that returns a Range object representing the area of a worksheet that is currently in use. This includes all cells that have ever contained data, formatting, or formulas, even if some of those cells are now empty. It is particularly useful for dynamically determining the extent of your data without needing to know the exact row and column boundaries beforehand. In xlwings, accessing this property allows you to programmatically interact with the actual used portion of a sheet, making your code more robust and adaptable to changing data sizes.

Syntax in xlwings:
The UsedRange property is accessed as an attribute of a Worksheet object. There are no parameters to specify.

used_range = ws.used_range

Here, ws is an xlwings Worksheet object (e.g., obtained via wb.sheets['Sheet1']). The returned used_range is an xlwings Range object. This Range object has properties like .address, .row, .column, .rows.count, and .columns.count which you can use to get the location and dimensions of the used area.

Key Functionality and Parameters:
Since UsedRange is a property, not a method, it does not take direct parameters. Its behavior is controlled by the state of the Excel worksheet. However, understanding what constitutes the “used range” is crucial:

  • Inclusion Criteria: Any cell that has ever been edited, formatted, or contained a formula is considered part of the used range. This means clearing cell contents might not remove it from the used range if formatting remains.
  • Dynamic Nature: The used range can expand when new data is added at its edges and can sometimes be reset by saving the workbook after deleting all content and formatting from unused cells.

Code Examples:
Here are practical examples of using ws.used_range in xlwings:

  1. Getting the Address and Dimensions:
import xlwings as xw
app = xw.App(visible=False)
wb = xw.Book('data.xlsx')
ws = wb.sheets[0]

used_rng = ws.used_range
print(f"Used Range Address: {used_rng.address}")
print(f"Number of used rows: {used_rng.rows.count}")
print(f"Number of used columns: {used_rng.columns.count}")
print(f"Top-left cell: ({used_rng.row}, {used_rng.column})")

wb.close()
app.quit()
  1. Clearing All Content and Formatting in the Used Range:
import xlwings as xw
wb = xw.Book('report.xlsx')
ws = wb.sheets['Summary']
ws.used_range.clear() # Clears both content and formatting
wb.save()
  1. Dynamically Reading All Data into a Python List:
import xlwings as xw
wb = xw.Book('inventory.xlsx')
ws = wb.sheets['Stock']

# Read all values from the used range into a 2D list
all_data = ws.used_range.value
for row in all_data:
    print(row)

# If you need the data as a pandas DataFrame
import pandas as pd
df = pd.DataFrame(all_data)
print(df.head())
  1. Applying Formatting to the Entire Used Area:
import xlwings as xw
from xlwings.constants import LineStyle
wb = xw.Book('financials.xlsx')
ws = wb.sheets['Q1']

used_rng = ws.used_range
# Add borders around all used cells
used_rng.api.Borders.LineStyle = LineStyle.xlContinuous
used_rng.api.Borders.Weight = 2
wb.save()

How to use Worksheet.Type in the xlwings API way

The Type member of the Worksheet object in the Excel object model represents the type of sheet, such as a standard worksheet, a chart sheet, or a macro sheet. In xlwings, this property is accessible via the api property, which provides direct access to the underlying Excel object model. This is particularly useful when you need to programmatically determine the nature of a sheet within a workbook, enabling conditional logic based on sheet type.

Functionality:
The primary function is to identify the sheet type. Common values include:

  • xlWorksheet (a standard worksheet, value -4167)
  • xlChart (a chart sheet, value -4109)
  • xlExcel4MacroSheet (an Excel version 4 macro sheet, value 3)
  • xlExcel4IntlMacroSheet (an international macro sheet, value 4)

Syntax:
The property is accessed through the xlwings Sheet object’s api property. The Sheet object in xlwings corresponds to both worksheets and chart sheets. The syntax is:

sheet_type = sheet.api.Type

Where sheet is an xlwings Sheet object. The Type property is read-only and returns an integer value (a XlSheetType enumeration constant).

Example:
The following xlwings code demonstrates how to check the type of each sheet in the active workbook and print a corresponding message. It uses the Type property via the api interface.

import xlwings as xw

# Connect to the active Excel instance and workbook
app = xw.apps.active
wb = app.books.active

# Iterate through all sheets in the workbook
for sheet in wb.sheets:
    sheet_type = sheet.api.Type

if sheet_type == -4167: # xlWorksheet
    print(f"Sheet '{sheet.name}' is a standard worksheet.")
elif sheet_type == -4109: # xlChart
    print(f"Sheet '{sheet.name}' is a chart sheet.")
elif sheet_type == 3: # xlExcel4MacroSheet
    print(f"Sheet '{sheet.name}' is an Excel 4 macro sheet.")
elif sheet_type == 4: # xlExcel4IntlMacroSheet
    print(f"Sheet '{sheet.name}' is an international macro sheet.")
else:
    print(f"Sheet '{sheet.name}' has an unknown sheet type: {sheet_type}")

# Example to check a specific sheet's type
target_sheet = wb.sheets['Sheet1']
if target_sheet.api.Type == -4167:
    print(f"\n'{target_sheet.name}' is confirmed to be a worksheet. Proceeding with data operations.")
    # Perform worksheet-specific tasks here, such as data manipulation
    target_sheet.range('A1').value = 'Data Entry Point'

How to use Worksheet.TransitionFormEntry in the xlwings API way

In the Excel object model, the TransitionFormEntry property of a Worksheet object is a legacy feature primarily used for compatibility with older Lotus 1-2-3 spreadsheet files. It controls how certain formula entries are interpreted when a worksheet is set to use transition formula evaluation. This property is rarely used in modern Excel automation, as its functionality pertains to specific backward-compatibility scenarios. However, for completeness, the xlwings library provides access to this property through its API, allowing developers to programmatically get or set its value when interfacing with Excel via Python.

Functionality:
The TransitionFormEntry property determines whether Excel uses transition formula entry rules for the specified worksheet. When enabled (set to True), Excel interprets formula prefixes like “+” or “@” according to Lotus 1-2-3 conventions, which can affect how formulas are entered and calculated. This is particularly relevant when working with sheets imported from or intended for older spreadsheet applications. The default value is False, meaning standard Excel formula evaluation is used.

Syntax in xlwings:
In xlwings, you can access this property through a Worksheet object. The property is exposed as a readable and writable attribute. The syntax is straightforward:

worksheet.transition_form_entry

This attribute returns or accepts a boolean value (True or False). There are no additional parameters, as it is a simple property rather than a method.

Code Example:
Below is a practical example demonstrating how to use the TransitionFormEntry property with xlwings. This script connects to an existing Excel workbook, accesses a specific worksheet, checks the current setting of TransitionFormEntry, modifies it, and then verifies the change. This example assumes you have xlwings installed and an Excel file named “example.xlsx” with a sheet called “Sheet1”.

import xlwings as xw

# Open the Excel workbook (ensure it's not open in Excel to avoid conflicts)
wb = xw.Book("example.xlsx")

# Access the specific worksheet
ws = wb.sheets["Sheet1"]

# Get the current TransitionFormEntry value
current_setting = ws.transition_form_entry
print(f"Current TransitionFormEntry setting: {current_setting}")

# Set TransitionFormEntry to True (enable Lotus 1-2-3 compatibility)
ws.transition_form_entry = True
print("TransitionFormEntry has been set to True.")

# Verify the change by retrieving the value again
updated_setting = ws.transition_form_entry
print(f"Updated TransitionFormEntry setting: {updated_setting}")

# Optionally, save the workbook to persist the change
wb.save()
wb.close()