Search code examples
pythonvbaxlwings

xlwings RunPython with function arguments


I am trying to run the RunPython function from a button in excel. I would like the function to take a parameter from a box in excel, something like this:

Sub ImportData()
    Dim choice As String
    choice = Range("B2").Value
    RunPython ("import Excel_module; Excel_module.importing_data(choice)")
End Sub

Is this a possibility? And if so how do I write the code? I would prefer not to use UDF.


Solution

  • You can do that in two ways:

    1) By using RunPython as you do:

    You'll need to use string concatenation:

    RunPython ("import Excel_module; Excel_module.importing_data(" & choice & ")")
    

    2) Or if you are on Windows only then you can also use the xw.sub decorator and use the imported function from VBA as if it was a native VBA function, see the docs. It isn't currently shown in the docs but they accept arguments.