使用 shell 指令在 vba 中执行批处理文件不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22380923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:20:14  来源:igfitidea点击:

executing batch file in vba using shell commend is not working

windowsexcelvbabatch-fileexcel-vba

提问by viji

i have created batch file to copy files from network drive to local.

我创建了批处理文件来将文件从网络驱动器复制到本地。

.bat file:

.bat 文件:

SET username=%1
SET password=%2
net use "\gesvij\toys\names" %password% /user:shop\%username%
:copy
Xcopy "\gesvij\toys\names" "%appdata%\Microsoft\Templates" /S /E
IF ERRORLEVEL 0 goto disconnect
goto end
:disconnect 
net use "\gesvij\toys\names" /delete
goto end
:end

i have tried the following code to execute the batch file in vba.

我已尝试使用以下代码在 vba 中执行批处理文件。

sub ok_click
dim un as string
dim pd as string
un = " " + un_text.value
pd = " " + pd_text.value

call shell("\gesvij\toys\names\test.bat & un & pd")
end sub

now i have following question:

现在我有以下问题:

1) the batch file is not running properly from vba code. but the bat file is working properly when i run independently. 2) once the file copied in the local how do i disconnect the network path "\gesvij\toys\names" in the batch file

1) 批处理文件未从 vba 代码正常运行。但是当我独立运行时,bat 文件工作正常。2)一旦文件复制到本地如何断开批处理文件中的网络路径“\gesvij\toys\names”

anyone please on this ?

有人请吗?

回答by Portland Runner

Your not adding in the un and pd variables correctly. They need to be outside of the quotes like this:

您没有正确添加 un 和 pd 变量。他们需要像这样在引号之外:

"\gesvij\toys\names\test.bat " & un & pd


Here is how I call a .bat file from VBA

这是我从 VBA 调用 .bat 文件的方法

Sub CreateReleasePart()
    Dim batPath As String: batPath = "C:\Users\sl\Desktop\"

    call Shell(Environ$("COMSPEC") & " /c " & batPath & "\myFile.bat", vbNormalFocus)
End Sub