Is xlwings in python able to pass =INDIRECT as a formula when using ws.range(cell).api.Validation.Add?

looking for some guidance. I’m trying to add validation to a range of cells in a .xlsm file. I want to dynamically add validation to some cells in column C, dependent on whether a value is present in column A. My code seems to correctly create the dynamic name “EndorsementRange” as I can verify it’s in the .xlsm file, but the validation itself is failing. Here’s the relevant portions of the code:

LIBRARIES

import openpyxl  # Library for reading and writing Excel files
from openpyxl.worksheet.datavalidation import DataValidation # Module to add data validation rules
from openpyxl.utils.dataframe import dataframe_to_rows  # Function to convert a DataFrame to rows for openpyxl
from openpyxl.workbook.defined_name import DefinedName  # Import for creating named ranges
import pandas as pd  # Data manipulation and analysis library
import win32com.client as win32  # Library for interacting with Excel and other Windows applications via COM
import xlsxwriter  # Library for creating Excel files with advanced formatting, charts, and images
import xlwings as xw  # Library for automating Excel with Python and enabling Python scripts within Excel
import os  # Library for interacting with the operating system, including file and directory operations
import time  # Library for adding delays

CODE THAT DEFINES THE NAMED RANGE AND ADDS IT TO THE .XLSM FILE

    # Check if the file exists
    if not os.path.exists(file_path):
        print(f"File '{file_path}' does not exist.")
        return
    
    # Load the workbook
    try:
        workbook = openpyxl.load_workbook(file_path, keep_vba=True)
    except Exception as e:
        print(f"Error loading workbook: {e}")
        return

    # Define the Named Range for the endorsements sheet column
    endorsements_sheet = workbook["endorsements"]
    max_row = endorsements_sheet.max_row
    endorsement_range = DefinedName('EndorsementRange', attr_text=f"'endorsements'!$A$2:$A${max_row}")
    workbook.defined_names.add(endorsement_range)

    # Save the workbook with openpyxl
    workbook.save(file_path)  

CODE THAT IS SUPPOSED TO ADD VALIDATION

    # Use xlwings to apply data validation
    app = xw.App(visible=False)
    wb = xw.Book(file_path)
    ws = wb.sheets['CSR24_Checklist']

   # Apply data validation using xlwings to ADD dynamic validation to cells C100-C140 if "Option 2: Existing Endorsement" is selected in column a on the same row.
    for row in range(100, 140):
        cell = f'C{row}'
        try:
            ws.range(cell).api.Validation.Delete()  # Clear any existing validation
            validation_formula = f'IF(A{row}="Option 2: Existing Endorsement", "EndorsementRange", "")'
            print(f"Applying validation to cell {cell} with formula: {validation_formula}")  # Debugging statement
            ws.range(cell).api.Validation.Add(
                Type=3,  # Type 3 is for list validation
                AlertStyle=1,
                Operator=1,
                Formula1=f'=INDIRECT({validation_formula})'
            )
            ws.range(cell).api.Validation.IgnoreBlank = True
            ws.range(cell).api.Validation.InCellDropdown = True
            ws.range(cell).api.Validation.ShowInput = True
            ws.range(cell).api.Validation.ShowError = True
            ws.range(cell).api.Validation.InputTitle = 'Select Endorsement'
            ws.range(cell).api.Validation.InputMessage = 'Select an endorsement from the list if "Option 2: Existing Endorsement" is selected in column A.'
            ws.range(cell).api.Validation.ErrorTitle = 'Invalid Entry'
            ws.range(cell).api.Validation.ErrorMessage = 'Invalid entry'
            print(f"Data validation applied to cell {cell} with formula =INDIRECT({validation_formula})")
        except Exception as e:
            print(f"Error applying data validation to cell {cell}: {e}")

        
    # Save and close the workbook with xlwings
    wb.save()
    wb.close()
    app.quit()

THE VALIDATION FAILS FOR EACH CELL, TERMINAL PRINTS THIS OUT FOR EACH CELL

Applying validation to cell C100 with formula: IF(A100="Option 2: Existing Endorsement", "EndorsementRange", "")
Error applying data validation to cell C100: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)

HOWEVER, THAT TYPE OF LOGIC WORKS FINE IF I DON’T USE INDIRECT() AS IN THIS CODE:

    for row in range(start_row, end_row):
        cell = f'A{row}'
        ws.range(cell).value = ''  # Add default value
        ws.range(cell).api.Validation.Delete()  # Clear any existing validation
        ws.range(cell).api.Validation.Add(
            Type=3,  # Type 3 is for list validation
            AlertStyle=1,
            Operator=1,
            Formula1="=validation_lists!$A$1:$A$2"
        )
        ws.range(cell).api.Validation.IgnoreBlank = True
        ws.range(cell).api.Validation.InCellDropdown = True
        ws.range(cell).api.Validation.ShowInput = True
        ws.range(cell).api.Validation.ShowError = True
        ws.range(cell).api.Validation.InputTitle = 'Endorsement Swap Options'
        ws.range(cell).api.Validation.InputMessage = 'Use "Option 1: New Endorsement" if the renewal attachment has not been uploaded to CSR24 yet.nnUse "Option 2: Existing Endorsement" if the attachment was previously uploaded to CSR24'
        ws.range(cell).api.Validation.ErrorTitle = 'Invalid Entry'
        ws.range(cell).api.Validation.ErrorMessage = 'Invalid entry'

I’ve tried hard coding the formula, i’ve tried using a helper function, both with the same results. When I used the help column that has this formula <IF(A{row}=”Option 2: Existing Endorsement”, “EndorsementRange”, “”> I could see the logic working based on the value in column A, and if I manually type the =INDIRECT formula into excel itself it works fine, and recognizes the defined name range.

Any guidance would be greatly appreciated!

New contributor

user26863337 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật