pythonexcelxlwings

Return multiple selected cells from excel into python via xlwings


I am trying to figure out how to pass several selected cells from excel into python via xlwings on macOS. I found code that passes cell notation but not all of the values.

For example: In my worksheet, I selected cells D8, D12, D18, and D21 having values of cell1, cell2, cell3, cell4

Code:

  wb   = xw.Book.caller()
  dbg = wb.sheets['debug']

  selected_range = wb.selection

  Print results in my debug worksheet

  dbg.range((1, 1)).value = selected_range.address

This is what gets printed: $D$8,$D$12,$D$18,$D$21

What I am looking for are the actual values of the cells.

I tried another example:

  cellRange = wb.app.selection
  rowNum = cellRange.row
  colNum = cellRange.column
  dbg.range((2, 1)).value = len(cellRange), rowNum, colNum

This is what printed $D$8,$D$12,$D$18,$D$21 1, 8, 4

The 1, 8, 4 corresponds to

cellRange = 1
rowNum = 8
colNum = 4

This says $D$8,$D$12,$D$18,$D$21 is one object and rowNum/colNum point to the first cell of the 4 I selected.

What am I missing? I want to return the values into my code to act on.

Thanks Dan


Solution

  • As suggested you would need loop the addresses or something similar.

    So you select the cells D8, D12, D18, and D21 then have the Python code split the range address and get the value for each.

    def main():
        wb = xw.Book.caller()
        dbg = wb.sheets['debug']
    
        selected_range = wb.selection
    
        # Values list 
        cell_values = [dbg[cell].value for cell in selected_range.address.split(',')]
    
        # Print results in my debug worksheet
        dbg.range((1, 1)).value = cell_values
    
    

    Example Output