Running a python script using VBA

Solution for Running a python script using VBA
is Given Below:

I’m trying to run a python script using a VBA script. However, I think VBA is having difficulties parsing the file paths of my python exe and python script. Please find below my code:

Sub RunPythonScript()
Dim shell As Object
Dim exePath As String, scriptPath As String
Dim waitOnReturm As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1


Set shell = VBA.CreateObject("Wscript.Shell")
exePath = """C:UsersDhruva RaoAppDataLocalProgramsPythonPython39python.exe"""
scriptPath = """G:Shared drivesProject Analysis TeamModel v3Codebasesingle_sitemain.py"""
shell.Run "cmd /k" & " " & exePath & " " & scriptPath

End Sub

Here’s a screenshot of the cmd prompt:
screenshot of error message

Appreciate any feedback on what’s wrong here.

Try this

exePath = "C:Users" & chr(34) & "Dhruva Rao" & chr(34) & "AppDataLocalProgramsPythonPython39python.exe""

The issue you see is that there is spaces in the paths. I have corrected this in the code below and adjusted, so instead of using the “”” I use chr(34), which inserts the quotation (“)-character inside the string. (I prefer this approach as it makes it clear where the quotation mark is intended.)

However, once that is fixed you will also experience issues with the cmd-part of your shell. The shell itself is the same as the cmd, so by choosing shell.run() you have essentially already started you cmd-prompt and you therefore need to specify which program to run (python.exe).

Sub RunPythonScript()
Dim shell As Object
Dim exePath As String, scriptPath As String
Dim waitOnReturm As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1


    Set shell = VBA.CreateObject("Wscript.Shell")
    exePath = "C:UsersDhruva RaoAppDataLocalProgramsPythonPython39python.exe"
    scriptPath = "G:Shared drivesProject Analysis TeamModel v3Codebasesingle_sitemain.py"
    shell.Run Chr(34) & exePath & Chr(34) & " " & Chr(34) & scriptPath & Chr(34)

End Sub