I am able to execute R in batch mode via Excel VBA with the code below, but this method limits interactivity because R closes after completion of the script. I would like to be able to make further calls to R based on Excel user input, while utilizing the R objects created in the first call. Is there a way to keep R active while still utilizing VBA to send messages to R?
Sub Run_R()
Dim shell As Object, Rcmd As String, retval As Variant
Set shell = VBA.CreateObject("WScript.Shell")
Rcmd = "Rscript C:\test.R"
retval = shell.Run(Rcmd, 0, True)
End Sub
Consider segmenting the two processes. Have Excel VBA obtain all needed user-input values through spreadsheet or userform, and then pass them into R script. R reads such values as command line args for a longer routine of operations.
Here, R is spawned as a child process in your application akin to aa separate macro or function which receives input parameters and processes an output:
VBA
Sub Run_R()
Dim shell As Object, Rcmd As String, retval As Variant
Dim var1, var2 As Double
var1 = Range("A2").Value
var2 = Range("A5").Value
Set shell = VBA.CreateObject("WScript.Shell")
Rcmd = "Rscript C:\test.R " & var1 & " " & var2
retval = shell.Run(Rcmd, 0, True)
End Sub
R
args <- commandArgs(trailingOnly=T)
var1 <- args[1]
var2 <- args[2]
# ... run other operations ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.