Search code examples
pythonpython-3.xexcelxlwings

How to return a range object from an xlwings function to Excel so that it can be used in formulas?


I'm trying to create a simple function in xlwings that takes a range object in the form of a cell, figures out what the last cell in the column of that cell with data is and then returns the range from the cell to the last cell with data. I then want to be able to use this range in a formula in Excel.

My issue is I can't get the return value to be a usable range object that excel can work with. How do I do that?

My function is (the function colnum_string just translates the numeric column to the excel column letter):

@xw.func
@xw.arg('start', 'range')
@xw.ret('end_range', 'range')
def CELLTOEND(start):
    column = colnum_string(start.column)
    row = start.row
    sheet = start.sheet
    end_row = xw.sheets[sheet].range(column + str(xw.sheets[sheet].cells.last_cell.row)).end(
        'up').row + 1
    end_range = xw.Range(column + str(row) + ":" + column + str(end_row))
    return end_range

This function gives me the compile error: xlret() takes from 0 to 1 positional arguments but 2 were given

I also tried to not create end_cell as Range object but to no avail and finally returning as end_cell.formula, which does return the range, but if that range contains the numbers from let's say 1-7, I cannot then use SUM on it and get the result of 28


Solution

  • I ended up doing this, which seems to work for my case:

    @xw.func
    @xw.arg('start', 'range')
    @xw.ret(transpose=True)
    def CELLTOEND(start):
        end=start.end('down')
        end_range=xw.Range(start,end)
        return end_range.value