通过excelvba运行python脚本

mfuanj7w  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(454)

我无法从excel vba运行python脚本。这是vba代码:

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

python代码如下所示。

print("hello")
input("hello, press enter")

当我运行vba时,python executer会打开,但会立即关闭,而不会实际执行脚本。换句话说,两者都不是 "hello" 也没有 "hello, press enter" 出现在python executer窗口上,该窗口突然关闭。
我确信python.exe和python脚本的路径是正确的。我两个都试过了 """""" 在这两种情况下,它都不起作用。很明显(非常简单!)如果我直接从python执行器运行python脚本,它就会工作。

eufgjt7s

eufgjt7s1#

你可能需要在两者之间留出空间 PythonExe & " " & PythonScript . 因此,您运行的命令是 "C:\…\python3.exe" "C:\…\BlackBoxAbsorbers.py" 在程序路径和python脚本之间留有空格。
还要注意 Dim PythonExe, PythonScript As String 只声明 PythonScript As String 但是 PythonExe As Variant . 在vba中,需要为每个变量指定一种类型: Dim PythonExe As String, PythonScript As String 或者是 Variant 默认情况下!
进一步的 objShell.Run PythonExe & PythonScript 无法正确调试。我建议将命令放入变量中,以便您能够在即时窗口中打印它以进行调试:

Dim Command As String
Command = PythonExe & PythonScript

Debug.Print Command

objShell.Run Command

如果执行此操作,您将看到命令的输出为:

"C:\Users\carlo\AppData\Local\Microsoft\WindowsApps\python3.exe""C:\Users\carlo\Desktop\MSc_Thesis\ML applications\BlackBox\BlackBoxAbsorbers.py"

两个字符串之间没有空格,实际上应该是:

"C:\Users\carlo\AppData\Local\Microsoft\WindowsApps\python3.exe" "C:\Users\carlo\Desktop\MSc_Thesis\ML applications\BlackBox\BlackBoxAbsorbers.py"

因此,我建议:

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

    Dim Command As String
    Command = PythonExe & " " & PythonScript

    objShell.Run Command
End Sub
7cwmlq89

7cwmlq892#

解决了的!!我不明白为什么,但是拆分objshell.run pythonexe和objshell.run pythonscript效果很好!就像这样:

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

无论如何谢谢@pᴇʜ,我认为你的回答是肯定的,因为你一直都很好!!

相关问题