是否可以从批处理文件中将错误代码返回给vba?

时间:2014-03-19 06:50:11

标签: excel vba batch-file excel-vba

我的批处理文件:

SET username=%1
SET password=%2

net use "\\gessel\toys\name" %password% /user:shops\%username%
ECHO.%ERRORLEVEL%
:copy
Xcopy "\\gessel\toys\name\babytoys" "%appdata%\shops" /S /E
ECHO.%ERRORLEVEL%

IF ERRORLEVEL 0 goto disconnect
goto end
:disconnect 
net use "\\gessel\toys\name\babytoys" /delete
goto end
:end
EXIT /B %ERRORLEVEL%

我从vba调用了上面的批处理文件,代码如下:

call Shell(Environ$("COMSPEC") & " /c " & path & username & password, vbHide)

上面的代码工作正常。但我需要验证文件是否在vba中复制。假设客户错误地输入了他的用户名和密码,那么他就不会得到玩具信息。然后我必须显示一个消息框,显示消息为"输入的信息错误"。所以为此我尝试了这样的代码:

sub submit_click

Dim as error as integer
error = Shell(Environ$("COMSPEC") & " /c " & path & username & password, vbHide)
if error <> 0
MsgBox "Provided info wrong", vbOKOnly, "Failure"
end if
end sub

但上面的代码不起作用。它总是返回值,即使用户名和密码是正确的。但如果我运行批处理文件,它会正确返回值,例如正确的详细信息0和错误的数据是2或4.请任何人帮我从批处理文件中捕获错误代码并将其传递给vba。

1 个答案:

答案 0 :(得分:4)

ERRORLEVEL变量的值随每个命令的执行而变化(或多或少)。因此,当批处理文件中的代码正在执行时,每个命令都会生成一个更改。您需要存储该值以供以后处理,或者在您的情况下,在每个步骤中使用相应的值退出:

SET "username=%~1"
SET "password=%~2"

rem This will be tested for a errorlevel value of 1 or greater. In this case, 
rem no further processing will be done if errors found, so we return our own 
rem value to the calling process

net use "\\gessel\toys\name" %password% /user:shops\%username% 
if errorlevel 1 exit /b 100

rem We are connected, and will disconnect no matter if xcopy worked or failed
rem So, the result of the command will be stored to later return the adecuate value

Xcopy "\\gessel\toys\name\babytoys" "%appdata%\shops" /S /E
set "exitCode=%errorlevel%"

net use "\\gessel\toys\name\babytoys" /delete

EXIT /B %exitCode%

现在,在vba代码中,error变量可以测试值100(我们从净使用中的错误返回的内容)或xcopy返回的任何值。

现在我们有了一个工作批处理文件,让我们来Excel。

NO,VBA中的Shell功能无法满足您的要求。 Shell的返回值是正在运行的进程的id。 Shell不等待进程结束,因此,它无法返回其退出代码。

但是,WshShell对象可以满足您的需求。

Dim oSHELL, batchFile, user, password, exitCode
    Set oSHELL = VBA.CreateObject("WScript.Shell")
    batchFile="myBatchFile.cmd"
    user="myUserName"
    password="this is my password"

    ' Quote strings to avoid problems with spaces
    ' The arguments are WhatToRun, WindowStyle (0=hide), WaitForProcessToEnd
    exitCode = oSHELL.Run(""""+batchFile+""" """+user+""" """+password+"""", 0, True)