Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Python script through Excel VBA

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.

like image 626
Carlo Cortellini Avatar asked Jan 18 '26 21:01

Carlo Cortellini


1 Answers

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!!

like image 70
Carlo Cortellini Avatar answered Jan 21 '26 11:01

Carlo Cortellini