从 R 运行 VBA 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19404270/
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 VBA script from R
提问by ddg
I have to manage a workflow involving R-scripts and VBA-code
.
I would like to run the process in R (where most of my code is) and now and then to call VBA-code
for specific calculation.
我必须管理一个涉及 R 脚本和VBA-code
. 我想在 R(我的大部分代码所在的地方)中运行该过程,然后不时调用VBA-code
特定的计算。
I would prepare the inputs for VBA in R, write somewhere the results (.csv, database) and then use the results in the rest of the R-script.
我会在 R 中准备 VBA 的输入,在某处写下结果(.csv,数据库),然后在 R 脚本的其余部分中使用结果。
The best would be of course to move the whole code into R but this is for now not possible. The VBA-code
is fairly complex. Translating this into R will be a challenging long-term task.
最好的当然是将整个代码移动到 R 中,但目前这是不可能的。该VBA-code
是相当复杂的。将其转换为 R 将是一项具有挑战性的长期任务。
Is there any possibility to manage in R such a work-flow?
有没有可能在 R 中管理这样的工作流程?
采纳答案by Richie Cotton
Write a VBscript wrapper that calls your VBA. See Way to run Excel macros from command line or batch file?
编写一个调用 VBA 的 VBscript 包装器。请参阅从命令行或批处理文件运行 Excel 宏的方法?
回答by lebelinoz
Here's a method which doesn't require a VBscript wrapper. You'll need to install the RDCOMClient
package
这是一个不需要 VBscript 包装器的方法。你需要安装这个RDCOMClient
包
library(RDCOMClient)
# Open a specific workbook in Excel:
xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open("C:\Temp\macro_template.xlsm")
# this line of code might be necessary if you want to see your spreadsheet:
xlApp[['Visible']] <- TRUE
# Run the macro called "MyMacro":
xlApp$Run("MyMacro")
# Close the workbook and quit the app:
xlWbk$Close(FALSE)
xlApp$Quit()
# Release resources:
rm(xlWbk, xlApp)
gc()