5

关于如何做到这一点的信息并不多。我尝试在线学习博客并在VBA中实现了以下代码(带有R文件的路径):-

Sub RunRscript()
    'runs an external R code through Shell
    'The location of the RScript is 'C:\R_code'
    'The script name is 'hello.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 = "RScript C:\R_code\hello.R"
    errorCode = shell.Run(path, style, waitTillComplete)
End Sub

资源

但是,当我在 Excel 中运行宏时,它基本上什么都不做——只是在 RStudio 中打开脚本。我没有收到任何错误,但它没有提供任何输出 - 只需在 Rstudio 中打开 R 脚本。我究竟做错了什么?

另外,如果我需要在 Excel 中使用 R,这种方法是否有效或者基本上我需要安装软件 RExcel?

任何其他在 Excel 中使用 R 的链接/信息将不胜感激。谢谢:)

4

2 回答 2

3

它在 RStudio 中打开似乎很奇怪。我建议直接通过 R.exe 运行它。根据您告诉我们的内容,PATH 似乎设置正确。因此,如果不需要输出,您可以像这样调用 R.exe:

Sub RunRscript()
    Shell ("R CMD BATCH C:\R_code\hello.R")
End Sub

如果你需要输出,那么你需要像这样创建一个 WshShell 对象:

Sub RunRscript()
    Dim output As String
    output = CreateObject("WScript.Shell").Exec("R CMD BATCH C:\R_code\hello.R").StdOut.ReadAll
End Sub

这是运行 R 脚本的较旧方法,但暂时应该可以正常工作。您可能需要进一步检查 R 的安装,看看是否还有其他问题。

于 2018-03-23T13:01:36.147 回答
0

我和你有同样的问题,但是“R CMD BATCH”解决方案对我不起作用。这对我有用。

首先,我测试了我是否可以通过命令行运行我的 R 脚本来排除任何问题。

打开命令提示符并尝试在“>”符号后键入“path Rscript.exe”“要运行的 R 脚本的路径”。在我的例子中,我输入了 "C:\Program Files\R\R-3.6.0\bin\Rscript.exe" "C:\Users\phung\Documents\Angela\DB_Import\TransformData.R" 然后回车运行代码。例如,请参见下图。您需要导航到您的 C 程序文件>R>版本>bin 以找到 Rscript.exe(可能是您计算机上的不同路径)。

在此处输入图像描述

一旦我得到这个工作,我在这里使用了 Ibo 提供的代码: Running R scripts from VBA

    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 Run_R 
        Dim iEerrorCode As Integer

        iEerrorCode = Run_R_Script("C:\Program Files\R\R-3.6.0\bin\Rscript.exe", """C:\Users\phung\Documents\Angela\1_MR-100 project\DB ready VBA code\TransformData.R""")
   End Sub

我小心翼翼地在 VBA 中使用双引号,因为我的文件夹名称中有一个空格。

于 2020-02-12T22:03:52.347 回答