1

我正在查看此处给出的答案如何使用 xlwings 从 Python 调用 Excel 宏?. 我实现了该解决方案,但测试调用 VBA 的可能性我想知道是否可以从我的 python 脚本调用使用 RunPython 的 VBA 函数。

为了说明这一点,我在文件夹中有三个文件

  • -- myproject.xlsm
  • --我的项目.py
  • -- Hello_World.py

myproject.xlsm 中的 VBA

Sub SampleCall()
    RunPython ("import myproject; myproject.xl_main()")
End Sub

Sub Hello()
    RunPython ("import Hello_World; Hello_World.xl_test()")
End Sub

Sub Message()
    MsgBox ("ok")
End Sub

我的项目.py

from xlwings import Workbook, Range, Application
import os
import sys


def xl_main():
    # Create a WorkBook Object
    wb = Workbook('myproject.xlsm')

    Range('B1').value = 17

    #Call a VBA Function
    Application(wb).xl_app.Run("Message")
    Application(wb).xl_app.Run("Hello")



if __name__ == "__main__":
    if not hasattr(sys, 'frozen'):
        # The next two lines are here to run the example from Python
        # Ignore them when called in the frozen/standalone version
        #TODO: Change the name of excel file
        path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'myproject.xlsm'))
        Workbook.set_mock_caller(path)
    xl_main()

Hello_World.py

import xlwings as xw
from xlwings import Workbook, Range

import os


def xl_test():
    # Create a WorkBook Object
    wb = xw.Workbook.caller()

    Range('A1').value = "Hello World"


if __name__ == '__main__':
    # To run from Python, not needed when called from Excel.
    # Expects the Excel file next to this source file, adjust accordingly.
    path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'myproject.xlsm'))
    xw.Workbook.set_mock_caller(path)
    xl_test()

问题:

问题是在我运行 Hello_World.py 脚本时它运行良好,但是当我在 VBA 中执行 SampleCall() Sub 时它崩溃并给出空白错误。

4

1 回答 1

0

您可以执行以下操作

xlwings - python 代码

wb.xl_workbook.Application.Run("someFunction", param1)

vba函数

Public Sub someFunction(param1)
    ...
End Sub
于 2016-08-04T15:47:19.153 回答