【问题标题】:Problem running Rscript in Excel 2013 through shell通过 shell 在 Excel 2013 中运行 Rscript 时出现问题
【发布时间】:2019-10-14 17:44:44
【问题描述】:

长期以来,我一直使用 vba 在 Excel 2010 和 Windows 7 中成功运行我的 r 脚本。然后我不得不使用另一台安装了 Excel 2013 和 Windows 8 的计算机。它给我以下错误:

对象“IWshShell3”的方法“运行”失败

这是在 Excel 2010 中运行的代码:

Dim shell As Object
Set shell = VBA.CreateObject("WScript.Shell")
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim style As Integer: style = 0
Dim errorCode As Integer
Dim var1 As String
Dim PATH As String

var1 = Replace(Replace(ThisWorkbook.PATH, "\", "/") & "/", " ", "_z9z_")

PATH = "C:\PROGRA~1\R_App\bin\x64\RScript """ & "C:\JF\Code A\dvlp.R"" " & var1 & " " & 2500

errorCode = shell.Run(PATH, style, waitTillComplete)

同样的代码不能在我提到的另一台计算机上运行。

我在 stackoverflow 中解决了其他问题,说明了同样的问题,但那里的解决方案对我没有帮助。例如,我已经使用了双引号,并且我已经尝试摆脱它们。

有什么想法吗?

【问题讨论】:

    标签: excel vba rscript wscript.shell


    【解决方案1】:

    考虑更简洁的命令行Rscript 调用构建,它可以处理名称中的空格,这可能是这里的问题。下面还集成了正确的错误处理。

    Sub Run_R_Script()
    On Error Goto ErrHandle
        Dim shell As Object
        Dim waitTillComplete As Boolean: waitTillComplete = True
        Dim style As Integer: style = 0
        Dim errorCode As Integer
    
        Dim args(0 To 3) As String
        Dim rCommand As String
        Dim i As Integer
    
        args(0) = "C:\PROGRA~1\R_App\bin\x64\RScript"
        'args(0) = "Rscript.exe"                          ' IF R BIN FOLDER IN PATH ENV VARIABLE
        args(1) = "C:\JF\Code A\dvlp.R"
        args(2) = Replace(Replace(ThisWorkbook.PATH, "\", "/") & "/", " ", "_z9z_")
        args(3) = 2500
    
        rCommand = args(0)
        For i = 1 To UBound(args)
            rCommand = rCommand & " """ & args(i) & """"
        Next i        
        Debug.Print rCommand                              ' CHECK COMMAND LINE CALL
    
        Set shell = VBA.CreateObject("WScript.Shell")
        errorCode = shell.Run(rCommand, style, waitTillComplete)
    
    ExitHandle:
        Set shell = Nothing                               ' RELEASE ALL set OBJECTS
        Exit Sub
    
    ErrHandle:
        MsgBox Err.Number & " - " & Err.Description, vbCritical
        Resume ExitHandle
    End Sub
    

    【讨论】:

    • 上述错误处理程序的错误是什么?请提供具体的错误编号。另外,您可以设置一个reproducible example 的示例脚本,它接受您的两个参数(即路径和编号)吗?我看不到你的ThisWorkbook.PATH。另外,发布解决方案中包含的命令Debug.Print
    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 2019-02-02
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多