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 inVBA
? 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))