WScript.Shell to run a script with spaces in path

2019-06-14 04:51发布

I need to call a script (R) from VBA using the WScript.Shell. The path to the file contains spaces. Additionally, a series of arguments is passed to the script, of which several also contain spaces.

I have tried all thinkable combinations of quotes and double quotes around paths, arguments or even the whole string (notably this here). Nothing seems to work when arguments need to be passed (I either get "C:\Program" not recognized"- or "invalid-syntax"-errors in the command line).

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

All of this is happening on Windows 7.

How can i run a command line script with spaces both in path and in the arguments to be passed? Any help greatly appreciated!

Update:

The code works if the prefix "cmd.exe /K " is removed from the command string. However, for testing and debugging, I would like to keep the shell window open once the script has run. How can this be achieved?

1条回答
该账号已被封号
2楼-- · 2019-06-14 05:22

enter image description hereI used to run scripts and pass arguments from Excel, this code works for me.

In order to run the script is very important that you first specify the path of your Rscript.exe and the path of your R script (.r file), then you can pass the arguments with spaces.

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 code to read the arguments:

args = commandArgs(trailingOnly = T)
cat(args[1])
查看更多
登录 后发表回答