VBA可以findR库

我正在尝试使用EXCEL作为R script的前端。 到目前为止,我在Windows CMDtesting了我的R script ,但无法使其在VBA工作。 错误消息是Error in library(readxl) : there is no package called 'readxl' 。 所以看起来VBA环境很挑剔。

  1. 有关修复此错误的任何build议? (现在修好)
  2. 有没有办法运行R script并将函数返回值(现在是5)保存到VBA的variables? 我可以通过保存一个文本文件并再次加载,但不知道是否有更好的方法来处理这个。

R脚本的一个简单的例子,它定义了一个函数并稍后调用它。

 est_var_dw <- function(){ library(readxl) library(minpack.lm) library(msm) return(2+3) } est_var_dw() 

一个简单的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 

更新

我想通过使用.libpath可以解决第一个问题是由于不同的R包的位置

 .libPaths(c(R_library_pth1, R_library_pth2)) 

在这里你的问题的第二部分有一个非常好的function: 从VBA中的shell命令捕获输出值?

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 

只要REST.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脚本打印到控制台的任何内容都将作为string返回到VBA