0

I need to run a python script from VBA. So far I managed to start python:

Sub py_launcher_test()
Dim objShell As Object
Dim PythonExe, PythonScript As String
Dim command As String

Set objShell = VBA.CreateObject("Wscript.Shell")


    PythonExe = "C:/Users/belose/PycharmProjects/week2/venv/Scripts/python.exe"

    command = Chr(34) & PythonExe & Chr(34) 
    objShell.Run command, 7, True

End Sub 

But when trying to run the specific script, the command prompt just flashes and disappears:

Sub py_launcher_test()
Dim objShell As Object
Dim PythonExe, PythonScript As String
Dim command As String

Set objShell = VBA.CreateObject("Wscript.Shell")


    PythonExe = "C:/Users/belose/PycharmProjects/week2/venv/Scripts/python.exe"
    PythonScript = "C:/Users/belose/PycharmProjects/week2/VGM/helloworld.py"
    command = Chr(34) & PythonExe & Chr(34) & " " & Chr(34) & PythonScript & Chr(34)
    objShell.Run command, 7, True

End Sub

What do I do wrong here?

UPD:

I tried the solutions from here:

Sub py_launcher_test2()

    RetVal = Shell("C:/Users/belose/PycharmProjects/week2/venv/Scripts/python.exe C:/Users/belose/PycharmProjects/week2/VGM/helloworld.py")

End Sub

Or:

Sub py_launcher_test3()
Dim Ret_Val
    args = """C:/Users/belose/PycharmProjects/week2/VGM/helloworld.py"""
    Ret_Val = Shell("C:/Users/belose/PycharmProjects/week2/venv/Scripts/python.exe " & " " & args, vbNormalFocus)
    If Ret_Val = 0 Then
         MsgBox "Couldn't run python script!", vbOKOnly
End If

End Sub

Or:

Sub py_launcher_test4()
    RetVal = Shell("C:/Users/belose/PycharmProjects/week2/venv/Scripts/python.exe C:/Users/belose/PycharmProjects/week2/VGM/helloworld.py", vbNormalFocus)
End Sub

All these attempts have the same result, the cmd just flashes and disappears. And that's how it looks like when I enter the command manually: cmd

Sergey Belousov
  • 153
  • 2
  • 12
  • Does this answer your question? [How to call python script on excel vba?](https://stackoverflow.com/questions/18135551/how-to-call-python-script-on-excel-vba) – razdi Feb 10 '20 at 06:32
  • @razdi No, I tried the options listed there, see the update for my post. – Sergey Belousov Feb 11 '20 at 11:21

1 Answers1

0

The solution is to add "cmd /k " at the beginning: RetVal = Shell("cmd /k " & "C:/Users/belose/PycharmProjects/week2/venv/Scripts/python.exe" & " " & "C:/Users/belose/PycharmProjects/week2/VGM/helloworld.py", vbNormalFocus)

Sergey Belousov
  • 153
  • 2
  • 12