运行 Python in VBA 其中执行路径中有空格

Running Python in VBA where there are spaces in execution path

我写了一个 Python 脚本来执行我想通过 Excel VBA 运行 的计算,并在 Excel 中显示结果。为了适用于不同的用户,我正在尝试编写一个代码,该代码将根据他们输入的用户名生成 Python 执行和 Python 脚本的路径,因为这是唯一会改变的东西路径。

有些人的用户名中有 space,这会导致在命令提示符中尝试 运行 Python 时出现问题。

有类似的问题,但我没有找到解决方案。我尝试在执行路径的开头和结尾添加三重双引号,例如

"""C:\Users\Claire Watson\anaconda3\python.exe"""

命令提示符中的结果类似于 'C:\Users\Claire' 无法识别。但是,这确实适用于 Python 脚本路径。

我还看到在 space 之前添加一个 ^ 可能会有所帮助,例如

"""C:\Users\Claire^ Watson\anaconda3\python.exe"""  

"C:\Users\Claire^ Watson\anaconda3\python.exe"  

结果是命令提示符显示 C:\Users\Claire: 无法打开文件 'Watson\anaconda3\python.exe: [Errno 2] 没有这样的文件或目录。

我也试过删除一些引号,但它指出存在语法错误或找不到路径。

我的代码:

Dim objShell As Object
Dim pythonexe As String
Dim pythonscript As String
Dim Username As String

Set objShell = VBA.CreateObject("Wscript.Shell")

Username = "Some name with or without spaces" 'dependent on the user input

pythonscript = """C:\Users\" & Username & "\........py"""

If InStr(Username, " ") > 0 Then ' Checks to see if there are spaces in username

    pythonexe = """C:\Users\" & Username & "\anaconda3\python.exe"""
    
    objShell.Run "cmd /k" & " " & pythonexe & " " & pythonscript
Else

     pythonexe = "C:\Users\" & Username & "\anaconda3\python.exe"
    
     objShell.Run "cmd /k" & " " & pythonexe & " " & pythonscript   ' This section gives no errors
     
End If

您的代码无效,因为您没有为您的用户名定义值。问题不是pythonexe路径不对。

尝试添加

Username = "Claire Watson"

它应该可以工作。

编辑:没有python进行测试所以这是我最好的最后一次尝试...

我发现令牌替换方法更简单:

Dim Username As String, cmd, root, qt

Username = "Some User"                        'dependent on the user input
qt = IIf(InStr(Username, " ") > 0, """", "")  'might need quotes

root = qt & "C:\Users\" & Username & "\"      'root directory with ending \

cmd = "cmd /k <python> <script> "  'cmd template with tokens

'replace tokens with values
cmd = Replace(cmd, "<python>", root & "anaconda3\python.exe" & qt)
cmd = Replace(cmd, "<script>", root & "blah.py" & qt)

Debug.Print cmd
'CreateObject("Wscript.Shell").Run cmd

cmd.exe 有非常讨厌的引用规则。但是,您应该能够引用 Python 解释器路径和脚本,这样无论用户名中是否有 space,它都能始终如一地工作。尝试这样的事情:

Dim objShell As Object
Dim pythonexe As String
Dim pythonscript As String
Dim Username As String
Dim cmd As String
'Double-quote character
Dim dq As String: dq = Chr(34)

Set objShell = VBA.CreateObject("Wscript.Shell")

Username = "Some name with or without spaces" 'dependent on the user input

pythonexe = dq & "C:\Users\" & Username & "\anaconda3\python.exe" & dq
pythonscript = dq & "C:\Users\" & Username & "\........py" & dq

cmd = "cmd /k " & dq & pythonexe & " " & pythonscript & dq
Debug.Print "Running command (" & cmd & ")"
objShell.Run cmd

正确引用的命令应如下所示(调试行将其打印到即时 Window 以进行调试):

cmd /k ""C:\Users\Claire Watson\anaconda3\python.exe" "C:\Users\Claire Watson\.........py""