带有函数参数的 xlwings RunPython

xlwings RunPython with function arguments

我正在尝试通过 excel 中的按钮 运行 RunPython 函数。我希望函数从 excel 中的框中获取参数,如下所示:

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

有这种可能吗?如果是这样,我该如何编写代码?我宁愿不使用 UDF。

您可以通过两种方式做到这一点:

1) 像您一样使用 RunPython

您需要使用字符串连接:

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

2) 或者,如果你只在 Windows 上,那么你也可以使用 xw.sub 装饰器并使用从 VBA 导入的函数,就好像它是本机函数一样 VBA函数,见docs。它当前未显示在文档中,但它们接受参数。