I´m trying to copy a R script from "Column 1" in Excel and paste it into Rstudio file "test2.R" and then run this code. I´m trying to do this using VBA. This is what I have now:
Public Sub RunRCode()
ActiveWorkbook.Save
Dim shell As Object
Set shell = VBA.CreateObject("WScript.Shell")
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim style As Long: style = 1
Dim errorcode As Long
Dim path As String
Dim var1 As String
var1 = Worksheets("Planilha2").Columns(1).Copy
path = """C:\RWindows\R-3.5.1\bin\Rscript.exe"" ""C:\Users\j042409\Desktop\test2.R"" """ & var1 & """"
errorcode = shell.Run(path, style, waitTillComplete)
End Sub
this VBA code is able to open the cmd windows but it seems that it isn´t able to paste the code from "Column 1" into RStudio. Any thoughts?
Try the following code as per my comment:
Sub RunRCode()
Dim fso As Object, ts As Object, shell As Object
Dim Rng As Range, path As String, exepath As String, errorcode As Long
'Creating R file from Excel
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = CreateObject("Scripting.TextStream")
path = "Path to file\filename.R"
Set ts = fso.CreateTextFile(path, True)
For Each Rng In Worksheets("Planilha2").UsedRange.Columns(1).Rows
If Not IsEmpty(Rng.Value) Then ts.WriteLine Rng.Value
Next
ts.Close
'Running R script
Set shell = VBA.CreateObject("WScript.Shell")
exepath = "path to Rscript.exe"
errorcode = shell.Run(exepath & " " & path, 1, True)
If errorcode <> 0 Then MsgBox "Error code: " & errorcode, vbCritical
End Sub
I got it using this code below!
Public Sub RunRCode()
ActiveWorkbook.Save
Dim shell As Object: Set shell = VBA.CreateObject("WScript.Shell")
Dim errorcode As Long
Dim path As String: path = "C:\RWindows\R-3.5.1\bin\Rscript.exe " & saveTempScript
errorcode = shell.Run(path, 1, True)
Kill saveTempScript
End Sub
Public Function saveTempScript() As String
Dim filePath As String
Dim i As Integer
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(Planilha2.Name)
filePath = "C:\Users\" & VBA.Environ("USERNAME") & "\Desktop\test3.r"
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim fileStream As TextStream
Set fileStream = fso.CreateTextFile(filePath)
For i = 1 To ws.Cells(ws.Cells.Rows.Count, "A").End(xlUp).Row
fileStream.WriteLine ws.Cells(i, 1).Value2
Next i
fileStream.Close
If Not fso.FileExists(filePath) Then
MsgBox "Arquivo não criado"
saveTempScript = vbNullString
GoTo try
Else
saveTempScript = filePath
End If
try:
Set fileStream = Nothing
Set fso = Nothing
End Function
Related
I run a Rscript from VBA, and currently my VBA code opens a shell of rscript.exe and the window do execute the script. It will run some code, but others it will close and send VBA message it has completed. Some of the code it does not like to run such as:
Excelticker <- (read_excel("ticker.xlsx",sheet="Tickers", range ="A1:A400"))
Excelticker <- Excelticker$Ticker
Excelticker <- na.omit(Excelticker)
financials <- getQuote(FirmsEG, what = yahooQF(c("P/E Ratio","Market Capitalization","Shares Outstanding","Currency","Earnings/Share")))
This is my VBA code
Public Sub Update()
Dim iEerrorcode As Integer
Dim MyRscript As String
Dim MyUpdate As String
MyRscript = "C:\Users\elowe\xxxx\M&A\models\test.R"
iEerrorcode = Run_R_Script(MyRscript)
MsgBox "Run"
End Sub
Function Run_R_Script(MyRscript As String, Optional RhomeDir As String = "C:\Program Files\R\R-4.2.2\bin\x64\Rscript.exe", Optional iStyle As Integer = 1, Optional bWaitTillComplete As Boolean = True) As Integer
Dim sPath As String
Dim shell As Object
'Define shell object
Set shell = VBA.CreateObject("WScript.Shell")
'Wrap the R path with double ""
sPath = """" & RhomeDir & """ """ & MyRscript & """"
'Run r using shell
Run_R_Script = shell.Run(sPath, iStyle, bWaitTillComplete)
End Function
I have tried several examples found on forums to run my R script from VBA, but it doesn't work. The R script works well alone. Here is the code I ran:
Sub RunRscript()
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 = "RScript C:\Users\Documents\Code.R"
errorCode = shell.Run(path, style, waitTillComplete)
End Sub
I'm getting an error message saying that running object "IWshShell3" failed. Is there anything special to write on the R code prior to running this macro? Shall I load a package, or load the files in a specific folder?
Your script is not able to find the executable (RScript).
Provide the absolute path, then it should work well.
See here on where to find it: http://datacornering.com/how-to-run-r-scripts-from-the-windows-command-line-cmd/
Edit:
I saw right now, that you could stumble into further problems regarding missing environments.
See here: Setting .libPaths() For Running R Scripts From Command Line Using Rscript.exe
This is how I would do it.
Sub RunRscript1()
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 to R executable: C:\your_path\Documents\R\R-3.2.5\bin\x64\R.exe
' path to R script: C:\your_path\Documents\R\Download.r
' see more setup details here
' http://shashiasrblog.blogspot.com/2013/10/vba-front-end-for-r.html
path = "C:\your_path\Documents\R\R-3.2.5\bin\x64\R.exe CMD BATCH --vanilla --slave C:\your_path\Documents\R\Download.r"
'path = """C:\your_path\Documents\R\R-3.2.5\bin\i386"" C:\Users\rshuell001\Documents\R\Download.R"
errorCode = shell.Run(path, style, waitTillComplete)
End Sub
Finally, here is a solution working well:
Function Run_R_Script(sRApplicationPath As String, _
sRFilePath As String, _
Optional iStyle As Integer = 1, _
Optional bWaitTillComplete As Boolean = True) As Integer
Dim sPath As String
Dim shell As Object
'Define shell object
Set shell = VBA.CreateObject("WScript.Shell")
'Wrap the R path with double quotations
sPath = """" & sRApplicationPath & """"
sPath = sPath & " "
sPath = sPath & sRFilePath
Run_R_Script = shell.Run(sPath, iStyle, bWaitTillComplete)
End Function
Sub Demo()
Dim iEerrorCode As Integer
iEerrorCode = Run_R_Script("C:\Program Files\R\R-3.6.1\bin\x64\Rscript",
"C:\Users\myname\Desktop\Code.R")
End Sub
I am trying to use EXCEL as the front end for a R script. So far, I tested my R script in Windows CMD but I could not make it work in VBA. The error message is Error in library(readxl) : there is no package called 'readxl'. So it looks like VBA environment is picky.
Any suggestions on fixing this error? (fixed now)
Is there a way to run R script and save the function returned value (now it is 5) into a variable in VBA? I can do this by saving a text file and load again, but not sure if there is a better way to handle this.
a simple example of R script, which defines a function and calls it later.
est_var_dw <- function(){
library(readxl)
library(minpack.lm)
library(msm)
return(2+3)
}
est_var_dw()
a simple example of VBA
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 = """" & Cells.Range("B1") & """ """ & Cells.Range("B2") & """ & Pause"
errorCode = shell.Run(path, style, waitTillComplete)
End Sub
Update
I figured out the first issue was due locations of different R packages, which can be solved by using .libpath
.libPaths(c(R_library_pth1, R_library_pth2))
There is a very good function for the second part of your question here: Capture output value from a shell command in VBA?
bburns-km defines a vba function ShellRun:
Public Function ShellRun(sCmd As String) As String
'Run a shell command, returning the output as a string'
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec(sCmd)
Set oOutput = oExec.StdOut
'handle the results as they are written to and read from the StdOut object'
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend
ShellRun = s
End Function
As long as RScript.exe is in your PATH, you can then call from VBA:
Sub Test()
Dim ScriptPath As String
Dim StringOut As String
ScriptPath = "C:\...\test.R" 'Your Path Here
'Assign
StringOut = ShellRun("RScript " & ScriptPath)
'Print
Debug.Print StringOut
End Sub
Anything that your R script prints to console during session will be returned to VBA as a string
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.
Public Sub RunRTest()
Shell ("Rscript test.r")
End Sub
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.
I put everything in a function that can be called easily. The output is the shell.run output, which is an integer:
Function to Run an R Script:
Function Run_R_Script(sRApplicationPath As String, _
sRFilePath As String, _
Optional iStyle As Integer = 1, _
Optional bWaitTillComplete As Boolean = True) As Integer
Dim sPath As String
Dim shell As Object
'Define shell object
Set shell = VBA.CreateObject("WScript.Shell")
'Wrap the R path with double quotations
sPath = """" & sRApplicationPath & """"
sPath = sPath & " "
sPath = sPath & sRFilePath
Run_R_Script = shell.Run(sPath, iStyle, bWaitTillComplete)
End Function
Examples how to call:
Sub Demo()
Dim iEerrorCode As Integer
iEerrorCode = Run_R_Script("C:\Program Files\R\R-3.4.4\bin\x64\rscript","C:\Ibos\R\WF_Metrics\Abe.R")
End Sub
OR
Sub Demo()
Dim iEerrorCode As Integer
Dim WS as WorkSheet
Set WS=ThisWorkBook.Worksheets("Sheet1")
iEerrorCode = Run_R_Script(WS.Range("A1"),WS.Range("A2")) 'cell A1=adderess of R application and cell A2 is the address of your R file, one can use a named range too
End Sub
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.
Public Sub RunRTest()
Shell ("Rscript test.r")
End Sub
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.
I put everything in a function that can be called easily. The output is the shell.run output, which is an integer:
Function to Run an R Script:
Function Run_R_Script(sRApplicationPath As String, _
sRFilePath As String, _
Optional iStyle As Integer = 1, _
Optional bWaitTillComplete As Boolean = True) As Integer
Dim sPath As String
Dim shell As Object
'Define shell object
Set shell = VBA.CreateObject("WScript.Shell")
'Wrap the R path with double quotations
sPath = """" & sRApplicationPath & """"
sPath = sPath & " "
sPath = sPath & sRFilePath
Run_R_Script = shell.Run(sPath, iStyle, bWaitTillComplete)
End Function
Examples how to call:
Sub Demo()
Dim iEerrorCode As Integer
iEerrorCode = Run_R_Script("C:\Program Files\R\R-3.4.4\bin\x64\rscript","C:\Ibos\R\WF_Metrics\Abe.R")
End Sub
OR
Sub Demo()
Dim iEerrorCode As Integer
Dim WS as WorkSheet
Set WS=ThisWorkBook.Worksheets("Sheet1")
iEerrorCode = Run_R_Script(WS.Range("A1"),WS.Range("A2")) 'cell A1=adderess of R application and cell A2 is the address of your R file, one can use a named range too
End Sub