我正在尝试使用EXCEL
作为R script
的前端。到目前为止,我在R script
中测试了我的Windows CMD
,但我无法在VBA
中使用它。错误消息为Error in library(readxl) : there is no package called 'readxl'
。所以看起来VBA
环境很挑剔。
R script
并将函数返回值(现在为5)保存到VBA
中的变量中?我可以通过保存文本文件并再次加载来完成此操作,但不确定是否有更好的方法来处理它。est_var_dw <- function(){
library(readxl)
library(minpack.lm)
library(msm)
return(2+3)
}
est_var_dw()
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
我发现第一个问题是不同R包的到期位置,可以使用.libpath
来解决
.libPaths(c(R_library_pth1, R_library_pth2))
答案 0 :(得分:1)
您的问题的第二部分有一个非常好的功能:Capture output value from a shell command in VBA?
bburns-km定义了一个vba函数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
只要RScript.exe在你的PATH中,你就可以从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
您的R脚本在会话期间打印到控制台的任何内容都将作为字符串
返回到VBA