Is there a way to call a Python code in Excel-VBA?

前端 未结 4 1840
暖寄归人
暖寄归人 2020-12-13 10:51

I have an Excel file (Main.xlsm) containing macros. I have a Python file (python.py) to generate a subsidiary Excel file (sub.xlsx) which I would further call in the macros

4条回答
  •  旧巷少年郎
    2020-12-13 11:21

    There are multiple ways tu run a python script with VBA depending on whether you need to wait for the end of the execution and know if it went without error.

    With Shell, asynchronous with console:

    Public Sub RunPython(file As String, ParamArray args())
      Shell "python.exe """ & file & """ " & Join(args, " ")
    End Sub
    

    With Shell, synchronous without console:

    Public Function RunPython(file As String, ParamArray args())
      Shell "pythonw.exe """ & file & """ " & Join(args, " ")
    End Function
    

    With WScript.Shell, synchronous without console and with exit code:

    Public Function RunPython(file As String, ParamArray args()) As Long
      Dim obj As Object
      Set obj = CreateObject("WScript.Shell")
      RunPython = obj.Run("pythonw.exe """ & file & """ " & Join(args, " "), 0, True)
    End Function
    

提交回复
热议问题