Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call python script from vba with wsh

I need to call a python script from vba which works fine by using the shell.

Sub CallPythonScript()

        Call Shell("C:\Program Files (x86)\Python27\python.exe C:\Users\Markus\BrowseDirectory.py")

End Sub

But when I try using wsh (because of the wait funcionality) it just won't work anymore.

Sub CallPythonScript()

    Dim wsh As Object
        Set wsh = VBA.CreateObject("WScript.Shell")

    Dim myApp As String: myApp = "C:\Program Files (x86)\Python27\python.exe C:\Users\Markus\BrowseDirectory.py"
    Dim waitOnReturn As Boolean: waitOnReturn = True
    Dim windowStyle As Integer: windowStyle = 1

    wsh.Run """"" & myApp & """"", windowStyle, waitOnReturn

End Sub

However, I used the same code at home and everything worked out just fine, with the difference that there weren't any blanks in the path. So naturally there must be something wrong with the blanks. Help is greatly appreciated.

like image 890
Billi B Avatar asked Apr 10 '26 21:04

Billi B


2 Answers

The interpreter cannot possibly distinguish directories containing spaces from real arguments unless you protect the directories with quotes.

A workaround, which is actually a better solution, relies on the fact that Python associates .py extension with the installed python interpreter.

Just do this (like you would launch a .bat file):

Dim myApp As String: myApp = "C:\Users\Markus\BrowseDirectory.py"

and your code will work no matter where python is installed (and the problem with spaces vanishes)

This little test in excel worked for me and ran pycrust.py which happens to be in my system PATH:

Sub foo()
  Dim wsh As Object
  Set wsh = VBA.CreateObject("WScript.Shell")

    Dim myApp As String: myApp = "pycrust.py"
    Dim waitOnReturn As Boolean: waitOnReturn = True
    Dim windowStyle As Integer: windowStyle = 1

    wsh.Run myApp, windowStyle, waitOnReturn

End Sub

(I had to simplify your wsh.Run line because it was not working, I suspect that the 256 quotes you added didn't do any good)

like image 107
Jean-François Fabre Avatar answered Apr 12 '26 10:04

Jean-François Fabre


Did you verify that path takes you directly to the interpreter?

Try this,

Dim myApp As String: myApp = "C:\""Program Files (x86)""\Python27\python.exe C:\Users\Markus\BrowseDirectory.py"
like image 24
Jimmy Smith Avatar answered Apr 12 '26 11:04

Jimmy Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!