1

I'm trying to create a button on Excel that runs an R script I created. This is the VBA code I tried:

Sub RunRscript()

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\Forecast.R"
errorCode = shell.Run(path, style, waitTillComplete)
End Sub

But that also returns an error -> Run-time error '-2147024894 (80070002) Automation Error.

I much appreciate any help!

8
  • Seems like if your R code has a problem then maybe address that first? Commented Sep 7, 2021 at 17:53
  • Well, I can run the Rcode on Rstudio error fee. Commented Sep 7, 2021 at 18:00
  • 2
    Use a fully qualified path to the executable you want to run. Your current code depends upon the PATH variable and lookup. Commented Sep 7, 2021 at 18:07
  • Where does your R script read its inputs from? Commented Sep 7, 2021 at 18:14
  • @HackSlash Can you elaborate on what a fully qualified path is? Or maybe tell me where to find more info about it? Thanks! Commented Sep 7, 2021 at 18:21

1 Answer 1

2

The answer was to use a fully qualified path to the executable you want to run in the shell. You can't rely on PATH variable lookups. It's much safer this way.

Sub RunRscript()

    Dim waitTillComplete As Boolean: waitTillComplete = True
    Dim style As Integer: style = 1
    Dim errorCode As Integer
    Dim path As String
    path = """C:\Program Files\R\R-4.1.1\bin\Rscript.exe"" C:\R_code\Forecast.R""

    With CreateObject("WScript.Shell")
        errorCode = .Run(path, style, waitTillComplete)
    End With
End Sub

NOTE: If you need to quickly find the location of an executable in your PATH variable you can run where RScript from cmd.exe and it will tell you the fully qualified path.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.