从批处理文件返回错误消息

时间:2014-11-24 03:06:55

标签: windows vba batch-file

我正在从VBA攻击批处理文件,以启动exec文件,例如Notepad.exe。如果找不到exec文件,我想将指示或消息返回给VBA。到目前为止,我一直在通过让bat将消息写入文本文件,然后让VBA检查此文件。这种方法看起来有点笨拙,但到目前为止我还没有遇到过另一种方法。

@echo off

set EM="C:\Msg.txt"
if exist %EM% del %EM%

set FL=%SystemRoot%\system32\xnotepad.exe

if not exist %FL% (
echo %FL% not found > %EM%
goto done
)

Start "" %FL%

:done

2 个答案:

答案 0 :(得分:2)

在VBA中

Dim oSHELL, batchname, usr, pass, exitcode
Set oSHELL = VBA.CreateObject("WScript.Shell")
usr="username"
pass="password"
batchname="batchFile.bat"

' Arguments ToRun, Style (0=hide), Waitforend
exitcode = oSHELL.Run(""""+batchname+""" """+usr+""" """+pass+"""", 0, True)

并在您的批次中

exit somenumber

应该{​​{1}}返回somenumber


我使用的实际代码:

exitcode

批处理Sub q27097252() Dim oSHELL, batchname, usr, pass, exitcode Set oSHELL = VBA.CreateObject("WScript.Shell") usr = "" pass = "" batchname = "c:\106x\q27097252.bat" ' Arguments ToRun, Style (0=hide), Waitforend exitcode = oSHELL.Run("""" + batchname + """ """ + usr + """ """ + pass + """", 0, True) MsgBox (exitcode) End Sub

c:\106x\q27097252.bat

在VBA代码编辑器/ F5中完全适合我(预期结果:消息框随机显示0..9)


使用Windows XP时的评论/解决方案:

@ECHO OFF SETLOCAL EXIT %time:~-1% GOTO :EOF 选项只会设置exit /b number,而errorlevel实际设置终止代码。
终止代码在XP下为0,因为exit number实际上正常终止 - 而Windows 7(及更高版本)似乎将当前cmd.exe指定为errorlevel进程的退出代码。
因此,请优先使用cmd.exe与XP兼容 - 代码经过调整以适应。

答案 1 :(得分:-1)

您可以使用EXIT命令执行此操作。看看EXIT /?

相关问题