Finding Range of active/selected cell in Excel using Python and xlwings
<p>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.</p>

<p>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.</p>

<p>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.</p>

<p>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':</p>

<pre><code>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
</code></pre>

<p>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'":</p>

<pre><code>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
</code></pre>

<p>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.</p>

<p>Thanks!</p>

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

<pre><code>cellRange = wb.app.selection
rowNum = cellRange.row
colNum = cellRange.column
</code></pre>

python xlwings