WScript.Shell 运行带有空格的脚本和来自 VBA 的参数

Sam*_*Sam 3 shell command-line vba rscript

我需要使用 WScript.Shell 从 VBA 调用脚本 (R)。文件路径包含空格。此外,还向脚本传递了一系列参数,其中一些还包含空格。

我已经在路径、参数甚至整个字符串周围尝试了所有可能的引号和双引号组合(特别是这里的)。当需要传递参数时,似乎没有任何工作(我要么在命令行中收到“C:\Program” not识别“-或”invalid-syntax“-错误)。

Option Explicit
Private Const QUOTE As String = """"

Sub test()
    Dim WS_Shell As Object
    Set WS_Shell = VBA.CreateObject("WScript.Shell")
    Dim err_code As Long

    Dim path As String
    Dim arg_1 As String
    Dim arg_2_with_spaces As String

    Dim complete_cmd_str As String

    path = "C:\Program Files\R\R-3.3.2\bin\Rscript.exe"
    arg_1 = "F:\path\to\my\script.R"
    arg_2_with_spaces = "A string-arg with spaces"

    complete_cmd_str = "cmd.exe /K " & QUOTE & path & QUOTE & " " _
                    & QUOTE & arg_1 & QUOTE & " " _
                    & QUOTE & arg_2_with_spaces & QUOTE

    Debug.Print complete_cmd_str
    err_code = WS_Shell.Run(complete_cmd_str, vbMinimizedNoFocus, True)
End Sub
Run Code Online (Sandbox Code Playgroud)

所有这些都发生在 Windows 7 上。

如何在路径和要传递的参数中运行带有空格的命令行脚本?非常感谢任何帮助!

更新:

如果从命令字符串中删除前缀“cmd.exe /K”,则代码有效。但是,为了测试和调试,我想在脚本运行后保持 shell 窗口打开。如何做到这一点?

war*_*_sc 5

在此处输入图片说明我曾经运行脚本并从 Excel 传递参数,这段代码对我有用。

为了运行脚本非常重要,首先指定 Rscript.exe 的路径和 R 脚本(.r 文件)的路径,然后您可以使用空格传递参数。

Sub run_R()

    Dim shell As Object
    Set shell = VBA.CreateObject("WScript.Shell")
    Dim waitTillComplete As Boolean: waitTillComplete = True
    Dim style As Integer: style = 1
    Dim errorcode As Integer
    Dim path As String

    path = Chr(34) & "C:\R\R-3.4.0\bin\i386\Rscript.exe" & Chr(34) & " " & Chr(34) & "C:\Users\userexample\Desktop\accionable.r" & Chr(34) & " " & Chr(34) & "Argument 1" & Chr(34)

    errorcode = shell.Run(path, style, waitTillComplete)

End Sub
Run Code Online (Sandbox Code Playgroud)

读取参数的R代码:

args = commandArgs(trailingOnly = T)
cat(args[1])
Run Code Online (Sandbox Code Playgroud)