vij*_*iji 2 excel vba batch-file
我的批处理文件:
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%
Run Code Online (Sandbox Code Playgroud)
我从VBA调用了上面的批处理文件,代码如下:
call Shell(Environ$("COMSPEC") & " /c " & path & username & password, vbHide)
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常。但我需要验证文件是否在 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
Run Code Online (Sandbox Code Playgroud)
但上面的代码不起作用。即使用户名和密码正确,它也始终返回该值。但是,如果我运行批处理文件,它会正确返回值,例如正确的详细信息为 0,错误的数据为 2 或 4。请任何人帮助我从批处理文件中捕获错误代码并将其传递到 VBA。
变量的值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%
Run Code Online (Sandbox Code Playgroud)
现在,在 vba 代码中,error可以测试变量的值 100(我们从 net use 错误返回的值)或从 xcopy 返回的任何值。
现在我们已经有了一个工作批处理文件,让我们转到 Excel。
不,ShellVBA 中的函数无法执行您所要求的操作。返回值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)
Run Code Online (Sandbox Code Playgroud)