Home » excel » Run a R script from a Macro (Excel)

Run a R script from a Macro (Excel)

Posted by: admin April 23, 2020 Leave a comment


I have an R script created but i don’t know how to source it from a Macro code in a xlsm file. I need to do it that way because I need to connect that macro with an interface in which I am working.

How to&Answers:

The simple way is probably to run a Shell function in you macro.

Shell "<your command>"

In this context, your command would be something like this depending on your R installation and the script location (source):

"C:\Program Files\R\R-3.4.3\bin\Rscript.exe" C:\Users\myusername\Documents\R\Send_Outlook_Email.R

Make sure you are able to run that command in the Command Prompt termnial as a test.

You can then replace the command that worked, but being careful to add the necessary double quotes. One way to have double quotes inside your string would be to use Chr(34). Eg.:

Shell Chr(34) & "C:\Program Files\R\R-3.4.3\bin\Rscript.exe" & Chr(34) & " C:\Users\myusername\Documents\R\Send_Outlook_Email.R"

Note that you might also need to add double quotes for the script path if it contains a space.