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:
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
args <- commandArgs(trailingOnly=T) var1 <- args var2 <- args # ... run other operations ...