如何捕获从VBA代码启动的Windows Shell脚本错误? [英] How to catch windows shell script errors launched from VBA code?

查看:174
本文介绍了如何捕获从VBA代码启动的Windows Shell脚本错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Shell函数从VBA启动批处理脚本:

I'm launching a batch script from VBA with the Shell function :

myRes = Shell("myScript.cmd")

有没有办法知道它是否成功运行或是否存在执行错误?

Is there a way to know if it runs successfully or if there were execution errors ?

推荐答案

我建议您尝试

I suggest you try the WshShell object instead of the native Shell function.

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1 'or whatever suits you best
Dim errorCode As Integer

errorCode = wsh.Run("myScript.cmd", windowStyle, waitOnReturn)

If errorCode = 0 Then
    MsgBox "Execution successful. No error to report."
Else
    MsgBox "Program exited with error code " & errorCode & "."
End If    

请注意:

如果bWaitOnReturn设置为false(默认值),则Run方法在启动程序后立即返回,并自动返回0(不会被解释为错误代码).

If bWaitOnReturn is set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).

因此,要检测程序是否成功执行,需要像上面的示例中那样将waitOnReturn设置为True.否则无论如何它都将返回零.

So to detect whether the program executed successfully, you need waitOnReturn to be set to True as in my example above. Otherwise it will just return zero no matter what.

我的早期答案可能也会有帮助.

这篇关于如何捕获从VBA代码启动的Windows Shell脚本错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆