在 VBA 宏中运行 R 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40349796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run R function in VBA macro
提问by lapioche75
I'm trying to run a R code from excel VBA macro.
我正在尝试从 excel VBA 宏运行 R 代码。
The R function is using two inputs: DataFilter(Input1,Input2) The function does some filtering and then saves a new excel file in the folder N:\DataFolder
R 函数使用两个输入: DataFilter(Input1,Input2) 该函数执行一些过滤,然后在文件夹 N:\DataFolder 中保存一个新的 excel 文件
Can you please help in creating an VBA macro that runs the DataFilter function with two new text inputs (lets say cells A1 and B1 from the sheet1 in the spreadsheet). From there I will be able to open the excel file in the vba macro.
您能否帮助创建一个运行带有两个新文本输入的 DataFilter 函数的 VBA 宏(比如电子表格中 sheet1 中的单元格 A1 和 B1)。从那里我将能够在 vba 宏中打开 excel 文件。
Thank you!
谢谢!
回答by yeedle
You can run an R script in VBA by creating Windows Shell obejct and passing it a string that executes an R script
您可以通过创建 Windows Shell 对象并将执行 R 脚本的字符串传递给它来在 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
(source)
(来源)
You can pass in your cell values as command line args to the R script. See ?commandArgs
for more.
您可以将单元格值作为命令行参数传递给 R 脚本。查看?commandArgs
更多。
回答by ghellquist
I am not sure this is a direct answer. You might want to look at how it is done using the Bert toolkit. This seems to help a lot in integrating R and Excel with each other.
我不确定这是一个直接的答案。您可能想看看它是如何使用 Bert 工具包完成的。这似乎有助于将 R 和 Excel 相互集成。