Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
adebouille-mercuria opened this issue May 16, 2024 · 3 comments
Open

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

adebouille-mercuria opened this issue May 16, 2024 · 3 comments

Comments

@adebouille-mercuria
Copy link

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
Copy link
Member

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

@adebouille-mercuria
Copy link
Author

adebouille-mercuria commented May 17, 2024 via email

@fzumstein
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants