How can I run a R script from VBA? Say I have a R script stored as C:\XXX\testR.R
I tried using Shell, but not quite successful.
Start with the default template and rename it as needed, placing it in an "r" subfolder of the folder where your Excel file is located. Copy excelhelper. r to the "r" folder created in step 1. Write the piece of code in VBA what will call your script first to get some data in the tmp folder before coding your R script.
To run an R command, put the cursor on the line of the command and then click the Run button at the top of the file window. Or just press CTRL-Enter.
Starting R If R has been installed properly, simply entering R on the command line of a terminal should start the program. In Windows, the program is typically specified as the action performed when clicking on an icon. You can also use this method on a *NIX system that has a window manager such as KDE.
Note be careful with your file locations and may need more explicit Shell dim statements....e.g. replace with these lines in your VB
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 = """" & Cells.Range("RhomeDir") & """ """ & Cells.Range("MyRscript") & """"
errorCode = shell.Run(path, style, waitTillComplete)
where, in Excel a cell with a named reference RhomeDir
contains text
C:\Program Files\R\R-3.2.3\bin\x64\rscript
and
MyRscript
contains text C:/Documents/Rworkings/Rscripttest.s
noting the unix R backslash and .s or .r postfix and VB replaces "" with " to give double brackets in path expression (plus further outside brackets to denote string). Also not a good idea to have spaces in your file name.
The full dim syntax of the shell command above was found by searching for VBA shell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With