来自 Excel VBA 函数的 xlwings 调用产生错误

xlwings call from Excel VBA function produces error

使用 xlwings 从 EXCEL sub 到 python 的调用工作正常,但是通过 VBA 函数触发相同的 VBA 会生成以下错误:

    Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\users\a112833\google drive\mytechtests\pulp\mymodule.py", line 13, in energySystemSimulator
    wb = Workbook.caller()
  File "C:\Python27\lib\site-packages\xlwings\main.py", line 233, in caller
    xl_app, xl_workbook = xlplatform.get_open_workbook(fullname, hwnd=sys.argv[4])
  File "C:\Python27\lib\site-packages\xlwings\_xlwindows.py", line 142, in get_open_workbook
    duplicate_fullnames = get_duplicate_fullnames()
  File "C:\Python27\lib\site-packages\xlwings\_xlwindows.py", line 124, in get_duplicate_fullnames
    for xl_app in get_xl_apps():
  File "C:\Python27\lib\site-packages\xlwings\_xlwindows.py", line 96, in get_xl_apps
    xl_app = get_xl_app_from_hwnd(hwnd)
  File "C:\Python27\lib\site-packages\xlwings\_xlwindows.py", line 73, in get_xl_app_from_hwnd
    return disp.Application
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.Application

这个有效:

Sub eSS()
    RunPython ("import mymodule; mymodule.eSS()")
End Sub

这打破了上面的回溯(忽略 fn.arguments):

Function fnESS(x As Double, y As Double) As Double
    Call eSS
    fnESS = ActiveWorkbook.Sheets("Config").Range("T10")
End Function

我检查过调用签名似乎使用 VBA 子或函数子调用完全相同。我看不出是什么导致了错误。

您在编写用户定义函数时看到了一个常见的陷阱:Excel 只允许您写入调用单元格,而不能写入调用单元格之外。这是 Excel 的限制,真的。

xlwings 可能会在某一天提供解决方法,但目前还没有官方支持。

附带说明:您实际上最好使用 xlwings 装饰器编写 UDF(至少如果您仅使用 Windows),请参阅 here.