0

很长时间以来,我一直使用 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中解决了其他问题,说明了同样的问题,但那里的解决方案并没有帮助我。例如,我已经使用了双引号,并且我已经尝试摆脱它们。

有任何想法吗?

4

1 回答 1

0

考虑一个更简洁的命令行调用构建,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
于 2019-10-14T19:46:05.163 回答