且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WScript.Shell运行脚本,在VBA的路径和参数中使用空格

更新时间:2023-10-18 14:53:28

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.

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])