HaRez
HaRez

Reputation: 49

Run Python Script via VBA from different Computers

I want to develop a tool where it is necessary to start a Python script via VBA.

I found the following code on the internet:

Sub RunPythonScript() '''This sub starts the Python script that creates the plots

    Dim objShell As Object
    ActiveWorkbook.Save
    Dim PythonExePath, PythonScriptPath As String

    Set objShell = VBA.CreateObject("Wscript.Shell")
    
    'PythonExePath = """C:\Users\MyName\AppData\Local\Programs\Python\Python38-32\python.exe""" ' 
    PythonScriptPath = "C:\Projects\MYproject\cttdb_plot_creator.py" 
    
    objShell.Run PythonExePath & PythonScriptPath

End Sub

This code works for me. However, when a colleague starts the tool from his computer, it does not work.

I think that I have entered too specific a path for "PythonExePath", namely: C:\Users\MyName\AppData\Local\Programs\Python\Python38-32\python.exe.

Is there a way to enter a path that is more general and works for every user?

Upvotes: 1

Views: 364

Answers (1)

Parfait
Parfait

Reputation: 107577

Simply have all users include the python.exe installation folder in their Path environment variable. On Windows which may require admin access, follow:

Control Panel > System and Security > System > Advanced system settings 
 > Environment Variables... > Path > OK > [Add new folder where python.exe resides]

See screenshot dialogs:

Windows Environment Path Dialogs

Verify with PowerShell ($Env:Path) or CMD Prompt (echo %Path%).

Once done, you can shorten your command line with:

PythonExePath = "python"
PythonScriptPath = "C:\Projects\MYproject\cttdb_plot_creator.py" 
    
objShell.Run PythonExePath & " " & PythonScriptPath

Upvotes: 1

Related Questions