Jim
Jim

Reputation: 3

Python: Passing Variable to Range()

Hi and thank you in advance.

Using Python 3.4 in Visual Studio 2015, to read/write from Excel 2007

Looking to pass a variable:

mylastrow ='$A$70006' # this address is not hard coded. it will be from an 'input'

Joining the above Range to the expression below is what i am failing at:

myrange = xlwings.Range('Sheet1', 'A2:' & lastrow).value

I have tried these:

myrange = xlwings.Range('Sheet1', 'A2:' & lastrow)
myrange = xlwings.Range('Sheet1', 'A2:' + lastrow).value
myrange = xlwings.Range('Sheet1', 'A2:' + lastrow)
myrange = xlwings.Range('Sheet1', 'A2:' & str(lastrow)).value
myrange = xlwings.Range('Sheet1', 'A2:' & int(lastrow)).value
myrange = xlwings.Range('Sheet1', 'A2:' + str(lastrow)).value
myrange = xlwings.Range('Sheet1', 'A2:' + int(lastrow)).value
myrange = xlwings.Range('Sheet1', 'A2', 'A' & lastrow).value
myrange = xlwings.Range('Sheet1', 'A2', 'A' & lastrow).value

I keep getting: 'unsupported operand type(s) for &: 'str' and 'int'' or 'Can't convert 'int' object to str implicitly'

Of course, after they are together, the address should look like A2:$A$70006

Even if you just have a link to a list of possible workarounds or just "this can't be done". Anything will well. Thank you again.

ps. For the forum itself, if i should have presented this in another way or should have structured this another way, please let me know so that I can fix it. thank you again.

Upvotes: 0

Views: 1086

Answers (1)

Ance
Ance

Reputation: 146

Try this

mylastrow ='$A$70006'
...
myrange = xlwings.Range('Sheet1', 'A2:{0}'.format(mylastrow)).value

More about python 3 string formatting can be read from here.

Upvotes: 1

Related Questions