gpt4 book ai didi

vba - 如何捕获从 VBA 代码启动的 Windows shell 脚本错误?

转载 作者:行者123 更新时间:2023-12-04 15:55:01 26 4
gpt4 key购买 nike

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

myRes = Shell("myScript.cmd")
有没有办法知道它是否运行成功或是否有执行错误?

最佳答案

我建议你试试WshShell对象而不是 native Shell 函数。

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

虽然请注意:

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 就像我上面的例子一样。否则无论如何它都会返回零。

This earlier answer of mine也可能有帮助。

关于vba - 如何捕获从 VBA 代码启动的 Windows shell 脚本错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11948771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com