VBA可以找到R库

时间:2016-07-15 09:42:43

标签: r excel vba excel-vba

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

  1. 有关修复此错误的任何建议吗? (现在修复)
  2. 有没有办法运行R script并将函数返回值(现在为5)保存到VBA中的变量中?我可以通过保存文本文件并再次加载来完成此操作,但不确定是否有更好的方法来处理它。
  3. 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
    

    更新

    我发现第一个问题是不同R包的到期位置,可以使用.libpath来解决

    .libPaths(c(R_library_pth1, R_library_pth2))
    

1 个答案:

答案 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