如何通过VBA调用RStudio执行指定R脚本?
解决方案
方案1:RStudio打开脚本时自动执行(推荐)
RStudio本身支持命令行参数--run,可以实现打开RStudio的同时自动执行指定R脚本,完全复用RStudio IDE的运行环境,解决RScript运行包异常的问题。
你原有代码仅实现了打开脚本文件,只需要调整命令拼接逻辑即可,修改后的完整VBA代码如下:
Sub RunRScript() Dim WshShell As Object Set WshShell = VBA.CreateObject("WScript.Shell") Dim waitTillComplete As Boolean: waitTillComplete = True Dim style As Integer: style = 1 Dim errorCode As Integer Dim RStudioPath As String, RCodePath As String ' 注意字符串路径需要用双引号包裹 RStudioPath = "C:\Program Files\RStudio\bin\rstudio.exe" RCodePath = "D:\rCode.R" ' 拼接命令,加入--run参数指定自动运行脚本 Dim path As String path = Chr(34) & RStudioPath & Chr(34) & " --run " & Chr(34) & RCodePath & Chr(34) errorCode = WshShell.Run(path, style, waitTillComplete) Set WshShell = Nothing End Sub
方案2:触发已经打开的RStudio运行当前脚本
如果需要控制已经打开的RStudio窗口执行代码,可以通过激活窗口+发送运行快捷键的方式实现,RStudio默认全脚本运行快捷键为Ctrl+Alt+R,代码如下:
Sub TriggerOpenedRStudioRun() Dim WshShell As Object Set WshShell = VBA.CreateObject("WScript.Shell") ' 激活RStudio窗口,括号内为RStudio窗口标题,一般格式为「脚本名 - RStudio」 AppActivate "rCode.R - RStudio" ' 等待1秒确保窗口激活成功 Application.Wait Now + TimeValue("00:00:01") ' 发送全量运行快捷键,^代表Ctrl,%代表Alt,{R}代表R键 WshShell.SendKeys "^%{R}" Set WshShell = Nothing End Sub
注意事项
- 若你自定义过RStudio的全脚本运行快捷键,需要对应修改
SendKeys后的快捷键参数 - 若脚本路径包含空格,必须用双引号包裹路径,上述代码中
Chr(34)即为双引号,已处理该场景 - 使用方案2时,需要确保RStudio窗口没有最小化,且对应脚本是当前激活的标签页
内容的提问来源于stack exchange,提问作者7hirumal
相关产品推荐
相关产品推荐

