Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running R scripts from VBA

Tags:

r

vba

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.

like image 589
Joyce Avatar asked Jul 22 '12 03:07

Joyce


People also ask

How do I run an R code in VBA?

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.

How do I run an R file in a 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.

How do I run an R script in terminal?

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.


1 Answers

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.

like image 76
hopethishelps Avatar answered Sep 28 '22 16:09

hopethishelps