Finding Range of active/selected cell in Excel using Python and xlwings

血红的双手。 提交于 2019-12-24 08:36:07

问题


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


来源:https://stackoverflow.com/questions/39901092/finding-range-of-active-selected-cell-in-excel-using-python-and-xlwings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!