Search code examples
pythonexcelselectionxlwings

xlwings looping through selected cells


I am using xlwings to interface with excel. I am attempting to loop through all selected cells.

The issue I am having is it doesn't just loop through the selected cells, it appears to loop through the range in-between as well. Is there a way to loop through just the selected cells with my selectedCells object?

I have B2, B5 and B6 selected. Excel Sheet

import xlwings as xw

awb = xw.books.active #sets active workbook
selectedCells = awb.app.selection

for value in selectedCells:
    print(value.raw_value)

Output 
CAT
BIRD
PIG

Expected output 
CAT
DOG
HORSE

Solution

  • One way is to split the address:

    for address in selectedCells.address.split(','):
        for cell in selectedCells.sheet.range(address):
            print(cell.raw_value)
    

    Output:

    CAT
    DOG
    HORSE
    

    EDIT:

    Use .api and then .Value.

    for cell in selectedCells.api:
        print(cell.Value)