Running R scripts from VBA

前端 未结 3 1354
囚心锁ツ
囚心锁ツ 2020-12-01 12:55

How can I run a R script from VBA? Say I have a R script stored as C:\\XXX\\testR.R

I tried using Shell, but not quite successful.

3条回答
  •  醉梦人生
    2020-12-01 13:49

    I put everything in a function that can be called easily. The output is the shell.run output, which is an integer:

    Function to Run an R Script:

    Function Run_R_Script(sRApplicationPath As String, _
                            sRFilePath As String, _
                            Optional iStyle As Integer = 1, _
                            Optional bWaitTillComplete As Boolean = True) As Integer
    
        Dim sPath As String
        Dim shell As Object
    
        'Define shell object
        Set shell = VBA.CreateObject("WScript.Shell")
    
        'Wrap the R path with double quotations
        sPath = """" & sRApplicationPath & """"
        sPath = sPath & " "
        sPath = sPath & sRFilePath
    
        Run_R_Script = shell.Run(sPath, iStyle, bWaitTillComplete)
    End Function
    

    Examples how to call:

    Sub Demo()
        Dim iEerrorCode As Integer
        iEerrorCode = Run_R_Script("C:\Program Files\R\R-3.4.4\bin\x64\rscript","C:\Ibos\R\WF_Metrics\Abe.R")
    End Sub
    

    OR

    Sub Demo()
        Dim iEerrorCode As Integer
        Dim WS as WorkSheet
    
        Set WS=ThisWorkBook.Worksheets("Sheet1")
        iEerrorCode = Run_R_Script(WS.Range("A1"),WS.Range("A2")) 'cell A1=adderess of R application and cell A2 is the address of your R file, one can use a named range too
    End Sub
    

提交回复
热议问题