【发布时间】:2012-07-22 03:43:36
【问题描述】:
如何从 VBA 运行 R 脚本?假设我有一个 R 脚本存储为 C:\XXX\testR.R
我尝试使用 Shell,但不太成功。
【问题讨论】:
如何从 VBA 运行 R 脚本?假设我有一个 R 脚本存储为 C:\XXX\testR.R
我尝试使用 Shell,但不太成功。
【问题讨论】:
Public Sub RunRTest()
Shell ("Rscript test.r")
End Sub
【讨论】:
请注意您的文件位置,可能需要更明确的 Shell dim 语句....例如用你的VB中的这些行替换
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("RhomeDir") & """ """ & Cells.Range("MyRscript") & """"
errorCode = shell.Run(path, style, waitTillComplete)
其中,在 Excel 中,具有命名引用 RhomeDir 的单元格包含文本
C:\Program Files\R\R-3.2.3\bin\x64\rscript 和
MyRscript 包含文本 C:/Documents/Rworkings/Rscripttest.s
注意 unix R 反斜杠和 .s 或 .r 后缀和 VB 将 "" 替换为 " 以在路径表达式中给出双括号(加上更远的括号以表示字符串)。在文件中包含空格也不是一个好主意名字。
通过搜索 VBA shell 可以找到上面 shell 命令的完整 dim 语法。
【讨论】:
我把所有东西都放在一个可以轻松调用的函数中。输出为shell.run输出,为整数:
运行 R 脚本的函数:
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 Demo()
Dim iEerrorCode As Integer
iEerrorCode = Run_R_Script("C:\Program Files\R\R-3.4.4\bin\x64\rscript","C:\Ibos\R\WF_Metrics\Abe.R")
End Sub
或
Sub Demo()
Dim iEerrorCode As Integer
Dim WS as WorkSheet
Set WS=ThisWorkBook.Worksheets("Sheet1")
iEerrorCode = Run_R_Script(WS.Range("A1"),WS.Range("A2")) 'cell A1=adderess of R application and cell A2 is the address of your R file, one can use a named range too
End Sub
【讨论】: