1

I am working with pywin32 and trying to get the R1C1 address of a specific cell. In VBA, you can use Range.Address(ReferenceStyle:=xlR1C1).

However, it appears that in pywin32, using Range.Address is not a method that allows for parameters, but instead is a property that just returns the string in the A1-style.

from win32com.client import Dispatch

xl = Dispatch("Excel.Application")
wb = xl.Workbooks.Open('my_workbook.xlsx')
sht = wb.sheets['Sheet1']

c = sht.Range("A1")
c.Address
# returns "$A$1"

c.Address(ReferenceStyle=-4150)
# TypeError: 'str' object is not callable
scotscotmcc
  • 2,719
  • 1
  • 6
  • 29

1 Answers1

1

The answer from @lifeisstillgood in this SO question gives a steer.

win32com gets around the issue of Property calls that take parameters (ie really are Methods in disguise) by quietly generating Get and/or Set methods.

The exact method will depend on how the Excel object is created.

  1. Using Dispatch() and late-binding. Here you seem to need to add the default parameters to the call, in the order here.
    xl=win32com.client.Dispatch('Excel.Application')
    ...
    c.GetAddress(True,True,-4150)
  1. Using EnsureDispatch() and early-binding. Here win32com generates Python wrappers, which allows the named parameters, and also generates the Excel constants.
    xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
    ...
    c.GetAddress(ReferenceStyle=win32com.client.constants.xlR1C1)

If you look in the Range.py wrapper, this function has been generated:

# The method GetAddress is actually a property, but must be used as a method to correctly pass the arguments
def GetAddress(self, RowAbsolute=defaultNamedNotOptArg, ColumnAbsolute=defaultNamedNotOptArg, ReferenceStyle=1, External=defaultNamedOptArg, RelativeTo=defaultNamedOptArg):
    # Result is a Unicode object
    return self._oleobj_.InvokeTypes(236, LCID, 2, (8, 0), ((12, 17), (12, 17), (3, 49), (12, 17), (12, 17)),RowAbsolute
                , ColumnAbsolute, ReferenceStyle, External, RelativeTo)
DS_London
  • 3,644
  • 1
  • 7
  • 24