WScript.Shell在VBA

时间:2018-04-04 13:42:53

标签: vba shell command-line rscript

我需要使用WScript.Shell从VBA调用脚本(R)。该文件的路径包含空格。另外,一系列参数传递给脚本,其中几个也包含空格。

我尝试过所有可行的引号和双引号组合,包括路径,参数甚至整个字符串(特别是this here)。当需要传递参数时,似乎没有任何作用(我得到" C:\ Program"无法识别" - 或"无效语法" - 命令行中的错误)。

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

所有这一切都发生在Windows 7上。

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

更新

如果前缀为" cmd.exe / K"从命令字符串中删除。但是,对于测试和调试,我想在脚本运行后保持shell窗口打开。如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

enter image description here我以前运行脚本并从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

读取参数的R代码:

args = commandArgs(trailingOnly = T)
cat(args[1])