How to use Application.GenerateTableRefs in the xlwings API way

The GenerateTableRefs member of the Application object in Excel is a method used to convert structured references from Excel tables into standard cell references (A1-style notation). This is particularly useful when you need to translate the user-friendly table column names, such as TableName[ColumnName], into the explicit range addresses that xlwings or other programming interfaces can directly manipulate. It simplifies dynamic range handling in macros or scripts when working with Excel Table objects.

Syntax in xlwings:

app.api.GenerateTableRefs(TableRef, UseTableNames, RefStyle)
  • TableRef: A required string argument that specifies the structured reference you want to convert. This can be a single table reference like "Sales[Amount]" or multiple references separated by commas.
  • UseTableNames: An optional Boolean argument. If set to True, the method returns references using table names (e.g., TableName[ColumnName]). If False or omitted, it converts to standard cell references (e.g., $A$1:$A$10). The default is False.
  • RefStyle: An optional constant from the XlReferenceStyle enumeration, which determines the reference style. The two primary values are:
  • xlwings.constants.xlA1: Returns references in A1-style (default).
  • xlwings.constants.xlR1C1: Returns references in R1C1-style.

Example:
Suppose you have an Excel workbook with a table named SalesData spanning columns A through C, and you want to convert the structured reference for the Revenue column into a standard range. Using xlwings, you can achieve this as follows:

import xlwings as xw

# Connect to the active Excel instance or open a workbook
app = xw.apps.active # or xw.App() for a new instance
wb = app.books['YourWorkbook.xlsx'] # Replace with your workbook name
ws = wb.sheets['Sheet1']

# Convert the table reference to A1-style cell references
table_ref = "SalesData[Revenue]"
converted_ref = app.api.GenerateTableRefs(TableRef=table_ref, UseTableNames=False, RefStyle=xw.constants.xlA1)

print(f"Converted reference: {converted_ref}") # Output might be something like "$C$2:$C$100"

# You can then use this reference in xlwings for operations, e.g., to get the range:
if converted_ref:
    revenue_range = ws.range(converted_ref)
    values = revenue_range.value # Retrieve values from the range
    print(f"Revenue values: {values}")

June 13, 2026 (0)


Leave a Reply

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