使用wsh从vba调用python脚本 [英] Call python script from vba with wsh

查看:65
本文介绍了使用wsh从vba调用python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从vba调用一个python脚本,该脚本可以通过使用Shell正常运行.

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

但是当我尝试使用wsh时(由于等待功能),它将不再起作用.

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.

推荐答案

除非您用引号保护目录,否则解释器可能无法区分包含空格的目录和实际参数.

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

一种变通方法,实际上是一个更好的解决方案,它依赖于Python将 .py 扩展名与已安装的python解释器相关联的事实.

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

只需执行此操作(就像您启动 .bat 文件一样):

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

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

无论您将python安装在哪里,代码都将正常运行(并且空格问题消失了)

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

这个excel中的小测试对我有用,并运行了 pycrust.py ,它恰好在我的系统 PATH 中:

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

(我不得不简化您的 wsh.Run 行,因为它行不通,我怀疑您添加的256个引号没有任何用处)

(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)

这篇关于使用wsh从vba调用python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆