xlwings / xlwings

xlwings is a Python library that makes it easy to call Python from Excel and vice versa. It works with Excel on Windows and macOS as well as with Google Sheets and Excel on the web.
https://www.xlwings.org
Other
2.95k stars 499 forks source link

UDF functions cannot return df as table in VBA function #2438

Open antoinedeb opened 4 months ago

antoinedeb commented 4 months ago

OS: Windows 10

Versions: xlwings 0.31.1, Python 3.10

Hello, I have defined a UDF py_return_df which works great as an Excel function. However, I want to use it in a VBA code linked to a button. In this case I get error, while it is the same function. Moreover, I managed to use simple UDF in VBA, but the ones returning tables don’t seem to work in VBA.

Thanks in advance for your help

Python UDF function

@xw.func
@xw.ret(header=True, index=True, expand='table')
def py_return_df():
    return pd.DataFrame(np.random.randn(5, 3), index=pd.date_range('1/1/2000', periods=5), columns=['A', 'B', 'C'])

VBA Sub

Sub Button4_Click()
    Dim ws As Worksheet
    Dim resultCell As Range
    Dim printDateResult As Range

    ' Set the worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    ' Define the target cell where the result will be placed
    Set resultCell = ws.Range("D60")

    ' Call the Python function to print the date
    Set printDateResult = py_return_df()

    ' Check if the result is not empty
    If Not printDateResult Is Nothing Then
        ' Place the result in the target cell
        printDateResult.Offset(1, 0).Resize(printDateResult.Rows.Count - 1, printDateResult.Columns.Count).Copy
        resultCell.PasteSpecial Paste:=xlPasteValues
        Application.CutCopyMode = False
    Else
        ' If the result is empty, display an error message
        MsgBox "Error: The result is empty."
    End If
End Sub

Error message in Excel

image

fzumstein commented 4 months ago

What's your use case to do this instead of using RunPython? See https://docs.xlwings.org/en/latest/quickstart.html#macros-call-python-from-excel

antoinedeb commented 4 months ago

I have very big functions with a Gurobi optimization. I need to give several parameters from the excel I have very big functions with a Gurobi optimization. I need to give several parameters from the excel to run the optim, which doesn’t seem possible with RunPython

fzumstein commented 4 months ago

Please provide (pseudo) code that reflects your actual use case.