Finding Range of active/selected cell in Excel usi

2019-07-27 02:46发布

问题:

I am trying to write a simple function in Python (with xlwings) that reads a current 'active' cell value in Excel and then writes that cell value to the cell in the next column along from the active cell.

If I specify the cell using an absolute reference, for example range(3, 2), then I everything is ok. However, I can't seem to manage to find the row and column values of whichever cell is selected once the function is run.

I have found a lot of examples where the reference is specified but not where the active cell range can vary depending on the user selection.

I have tried a few ideas. The first option is trying to use the App.selection that I found in the v0.10.0 xlwings documentation but this doesn't seem to return a range reference that can be used - I get an error "Invalid parameter" when trying to retrieve the row from 'cellRange':

def refTest():

import xlwings as xw

wb = xw.Book.caller()

cellRange = xw.App.selection

rowNum = wb.sheets[0].range(cellRange).row
colNum = wb.sheets[0].range(cellRange).column

url = wb.sheets[0].range(rowNum, colNum).value

wb.sheets[0].range(rowNum, colNum + 1).value = url

The second idea was to try to read the row and column directly from the cell selection but this gives me the error "Property object has no attribute 'row'":

def refTest():

import xlwings as xw

wb = xw.Book.caller()

rowNum = xw.App.selection.row
colNum = xw.App.selection.column

url = wb.sheets[0].range(rowNum, colNum).value

wb.sheets[0].range(rowNum, colNum + 1).value = url

Is it possible to pass the range of the active/selected cell from Excel to Python with xlwings? If anyone is able to shed some light on this then I would really appreciate it.

Thanks!

回答1:

You have to get the app object from the workbook. You'd only use xw.App directly if you wanted to instantiate a new app. Also, selection returns a Range object, so do this:

cellRange = wb.app.selection
rowNum = cellRange.row
colNum = cellRange.column