How to use Range.Dirty in the xlwings API way

The Dirty member of the Range object in Excel’s object model is a method used to mark a specific range of cells as “dirty,” meaning they have been modified or edited. This is particularly useful in scenarios involving calculation dependencies or when you need to force a recalculation for specific cells without recalculating the entire workbook. In xlwings, the Dirty method can be accessed through the api property, which provides direct access to the underlying Excel object model. This allows for precise control over calculation triggers in automated Excel tasks.

Functionality
The primary function of the Dirty method is to flag a range as changed, prompting Excel to recalculate any formulas that depend on the cells within that range during the next calculation cycle. This can improve performance by avoiding full workbook recalculations and ensuring that only relevant parts of the spreadsheet are updated. It is especially beneficial in large workbooks with complex formulas or data models where selective recalculation is needed.

Syntax
In xlwings, the Dirty method is called using the api property on a Range object. The syntax is as follows:
range.api.Dirty()
Here, range refers to an xlwings Range object representing the cells you want to mark as dirty. The method does not take any parameters. It directly applies to the specified range, marking all cells within it as modified.

Example
Consider a scenario where you have an Excel workbook with formulas in column B that depend on values in column A. After updating some cells in column A programmatically using xlwings, you can use the Dirty method to ensure that the dependent formulas in column B are recalculated. Below is a code example demonstrating this:

import xlwings as xw

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

# Update values in column A (e.g., cells A1:A5)
for i in range(1, 6):
    sheet.range(f'A{i}').value = i * 10 # Set values to 10, 20, ..., 50

# Mark the updated range as dirty to trigger recalculation of dependent formulas
sheet.range('A1:A5').api.Dirty()

# Optional: Force a calculation if automatic calculation is disabled
wb.app.calculate()

# Read the results from column B to verify recalculation
for i in range(1, 6):
    result = sheet.range(f'B{i}').value
    print(f'Cell B{i} value after dirty mark: {result}')

October 27, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *