I have trouble running a python script from Excel VBA. This is the VBA code:
Sub RunPython()
Dim objShell As Object
Dim PythonExe, PythonScript As String
Set objShell = VBA.CreateObject("Wscript.Shell")
PythonExe = """C:\Users\carlo\AppData\Local\Microsoft\WindowsApps\python3.exe"""
PythonScript = """C:\Users\carlo\Desktop\MSc_Thesis\ML applications\BlackBox\BlackBoxAbsorbers.py"""
objShell.Run PythonExe & PythonScript
End Sub
The python code is the following.
print("hello")
input("hello, press enter")
When I run VBA, the python executer opens but it immediately closes without actually executing the script. In other words, neither "hello" nor "hello, press enter" appear on the python executer window, which suddenly closes.
I'm sure the paths to the python.exe and to the python script are correct. I've tried them both with """" and with "" and in both cases it does not work. Obviously (it's super simple!) the python script works if I run it directly from the python executer.
SOLVED!! I can't understand why, but splitting objShell.Run PythonExe and objShell.Run PythonScript it works fine! Like that:
Public Sub RunPython()
Dim objShell As Object
Set objShell = VBA.CreateObject("Wscript.Shell")
Dim PythonExe As String
PythonExe = """C:\Users\carlo\AppData\Local\Microsoft\WindowsApps\python3.exe"""
Dim PythonScript As String
PythonScript = """C:\Users\carlo\Desktop\MSc_Thesis\ML applications\BlackBox\BlackBoxAbsorbers.py"""
objShell.Run PythonExe
objShell.Run PythonScript
End Sub
Thanks anyway @Pᴇʜ , I'll rate your answer as positive 'cause you have been very kind!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With