2012-07-22 139 views
10

如何从VBA运行R脚本?说我有一个R脚本存储为C:\ XXX \ testR.R从VBA运行R脚本

我尝试使用壳牌,但不是很成功。

回答

18
Public Sub RunRTest() 
    Shell ("Rscript test.r") 
End Sub 
+0

简单而伟大,非常感谢! – Joyce 2012-07-22 08:49:30

7

请注意您的文件位置,可能需要更多的显式的Shell语句。在你的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 \ 64 \ RSCRIPT和

MyRscript包含文本“C:/Documents/Rworkings/Rscripttest.s”

注意到UNIX的r反斜线和.S或.R后缀和VB替换“”具有“,得到在路径表达式双括号(加进一步在括号内表示字符串)。也不是一个好主意有空格在你的文件名中。

通过搜索VBA shell找到上述shell命令的完整dim语法。