How to use Worksheet.FilterMode in the xlwings API way

The FilterMode property of a Worksheet object in the xlwings API is a read-only property that returns a Boolean value indicating whether the worksheet currently has any active autofilters applied. Specifically, it checks if the worksheet is in “filter mode,” meaning one or more columns have filter dropdowns enabled due to an autofilter being turned on. This is useful for programmatically determining the state of filters before performing operations like data processing or clearing filters, ensuring that your automation scripts can adapt dynamically to the worksheet’s condition.

Syntax and Parameters:
In xlwings, you access this property through a Sheet object (which corresponds to an Excel worksheet). The property does not take any arguments.

sheet.api.FilterMode

Here, sheet is an xlwings Sheet object. The .api attribute provides direct access to the underlying Excel object model (via COM on Windows or AppleScript on macOS), allowing you to use properties like FilterMode as defined in the Excel VBA documentation. The property returns True if the worksheet is in filter mode, and False otherwise.

Code Examples:
Below are practical examples of using the FilterMode property in xlwings:

  1. Checking Filter Mode State:
    This example opens an Excel workbook, selects a specific sheet, and checks if filters are active.
import xlwings as xw

# Open the workbook and reference the sheet
wb = xw.Book("example.xlsx")
sheet = wb.sheets["Sheet1"]

# Check if the sheet is in filter mode
if sheet.api.FilterMode:
    print("The worksheet has active autofilters.")
else:
    print("No autofilters are currently applied.")
  1. Conditional Operations Based on Filter Mode:
    This script uses FilterMode to decide whether to clear existing filters before applying new ones, preventing errors or unintended behavior.
import xlwings as xw

wb = xw.Book("data.xlsx")
sheet = wb.sheets[0]

# If filters are already on, clear them
if sheet.api.FilterMode:
    sheet.api.AutoFilterMode = False # Turn off autofilter mode
    print("Existing filters cleared.")

# Apply a new autofilter to a range (e.g., A1:D100)
sheet.range("A1:D100").api.AutoFilter(1)
print("New autofilter applied.")
  1. Monitoring Filter Changes:
    In a more dynamic scenario, you might loop through multiple sheets to report their filter status.
import xlwings as xw

wb = xw.Book("report.xlsx")

for sheet in wb.sheets:
    status = "Active" if sheet.api.FilterMode else "Inactive"
    print(f"Sheet '{sheet.name}' has filters: {status}")

September 22, 2026 (0)


Leave a Reply

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