【问题标题】:Why VB Shell function does not stop Python code execution window?为什么 VB Shell 函数不会停止 Python 代码执行窗口?
【发布时间】:2021-09-05 16:27:11
【问题描述】:

使用 excel VB Shell 函数执行 python 代码不会停留在 python 指令处。它快速打开和关闭,但不显示 Python 指令。以下excel宏运行python代码:

Sub run_python()
    
    python_exe = "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe"
    python_script = "C:/Users/Goerge/OneDrive - MS Corporation/Documents/Development/python-excel/excel_python.py"
    
    If Dir(python_exe) = "" Then
    MsgBox ("Python executable does not exists")
    End If
    
    If Dir(python_script) = "" Then
    MsgBox ("Python script does not exists")
    End If
    
    python_code = python_exe & " " & " -k " & python_script
    
    RetVal = Shell(python_code)
    
End Sub

示例python代码:

import os
    
print("This is first python function called in excel")
for x in range(0,9999999999999999999):
    print("Counting : ", x)
    #input('Press ENTER to exit')
os.system("pause")

我在这里添加了几个步骤(for循环和“暂停”)来保持代码执行,但通过宏执行时它没有响应。但是,当直接在 VS 代码中运行时,此代码可以正常工作。

我在这里做错了什么?

我正在使用 Excel 365 和 Python 3.7。

【问题讨论】:

    标签: python excel vba shell


    【解决方案1】:

    问题与路径中的空格有关。 python 路径中的空格很好,但 Python 脚本路径不应该有任何空格。当有空格时,它被分成单独的变量,并且永远不会将脚本视为文件。所以解决方法是用双引号对带有空格的路径进行引用。

    VB 脚本应该如下:

    Sub run_python()
    
    python_exe = "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe"
    python_script = "C:/Users/Goerge/OneDrive - MS Corporation/Documents/Development/python-excel/excel_python.py"
    
    If Dir(python_exe) = "" Then
        MsgBox ("Python executabl does not exists")
    End If
    
    If Dir(python_script) = "" Then
        MsgBox ("Python script does not exists")
    End If
    
    python_code = python_exe & " " & """" & python_script & """"
    MsgBox python_code
    RetVal = Shell(python_code)
    
    'Shell "pskill " & " " & RetVal
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 2012-08-24
      相关资源
      最近更新 更多