Running R scripts from VBA

前端 未结 3 1357
囚心锁ツ
囚心锁ツ 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:33

    Note be careful with your file locations and may need more explicit Shell dim statements....e.g. replace with these lines in your VB

    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 = """" & Cells.Range("RhomeDir") & """ """ & Cells.Range("MyRscript") & """"
    
    errorCode = shell.Run(path, style, waitTillComplete)
    

    where, in Excel a cell with a named reference RhomeDir contains text

    C:\Program Files\R\R-3.2.3\bin\x64\rscript and

    MyRscript contains text C:/Documents/Rworkings/Rscripttest.s

    noting the unix R backslash and .s or .r postfix and VB replaces "" with " to give double brackets in path expression (plus further outside brackets to denote string). Also not a good idea to have spaces in your file name.

    The full dim syntax of the shell command above was found by searching for VBA shell.

提交回复
热议问题