in 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
应该返回somenumber
to 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
@ECHO OFF
SETLOCAL
EXIT %time:~-1%
GOTO :EOF
在 VBA 代码编辑器/F5 中运行得非常好(预期结果:消息框随机显示 0..9)
使用 Windows XP 时的以下评论/解决方案:
会出现exit /b number
选项只是设置errorlevel
然而exit number
实际上设置终止代码。
XP 下终止代码为 0,因为cmd.exe
实际上正常终止 - 而 Windows 7(及更高版本)似乎分配当前errorlevel
作为退出代码cmd.exe
过程。
因此,使用exit number
优先考虑与 XP 的兼容性 — 代码经过调整以适应。