我在看这里给出的答案How do I call an Excel macro from Python using xlwings?。我实现了这个解决方案,但测试了调用VBA的可能性我想知道是否可以从我的python脚本中调用使用RunPython的VBA函数。
为了说明这一点,我在文件夹
中有三个文件myproject.xlsm中的VBA
b
myproject.py
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
Hello_World.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脚本时效果很好,但是当我在VBA中执行SampleCall()Sub时它崩溃并出现空白错误。
答案 0 :(得分:0)
您可以执行以下操作
xlwings - python代码
wb.xl_workbook.Application.Run("someFunction", param1)
vba fucntion
Public Sub someFunction(param1)
...
End Sub