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?
I 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.
R code to read the arguments: