简体   繁体   English

如何在 Wscript.Shell + cmd.exe 中使用变量?

[英]How to use variables in Wscript.Shell + cmd.exe?

I'm trying to substitute variables to path in a wsh.run command (it should launch a batch file), but I got an error in the dos console: "The file name, directory name or volume label syntax is incorrect".我正在尝试将变量替换为 wsh.run 命令中的路径(它应该启动一个批处理文件),但在 dos 控制台中出现错误:“文件名、目录名或卷 label 语法不正确”。

Here the code that works:这是有效的代码:

Sub TestDos()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim fBatFile As String
Dim ErrorCode As Integer
Dim wkPath As String
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wkPath = Application.ActiveWorkbook.Path
fBatFile = wkPath & "\run.bat"

ErrorCode = wsh.Run("cmd.exe /c cd /d G:\Projects && G:\Projects\run.bat", windowStyle, waitOnReturn)
Debug.Print ErrorCode

End Sub

I tried with:我试过:

ErrorCode = wsh.Run("cmd.exe /c cd /d wkPath && fBatFile", windowStyle, waitOnReturn)

Or:或者:

ErrorCode = wsh.Run("cmd.exe /K cd /d " & wkPath & fBatFile & "", windowStyle, waitOnReturn)

but it doesn't work.但它不起作用。 Anyone can help me, please?任何人都可以帮助我,好吗?

I found the solution:我找到了解决方案:

ErrorCode = wsh.Run("cmd.exe /c cd /d " & wkPath & " && " & fBatFile, windowStyle, waitOnReturn) ErrorCode = wsh.Run("cmd.exe /c cd /d " & wkPath & " && " & fBatFile, windowStyle, waitOnReturn)

I can't find a clear webpage that explain when and how we need '&' and "".我找不到一个清晰的网页来解释我们何时以及如何需要“&”和“”。 The official documentation is very obscure for me.官方文档对我来说非常模糊。

Anyway, even this time, it's done!无论如何,即使是这一次,也完成了!

PS: If I use "cmd.exe /k" (I hold the dos console open), instead of '/c', the VBA Editor give me a "Overflow" error. PS:如果我使用“cmd.exe /k”(我打开 dos 控制台),而不是“/c”,VBA 编辑器会给我一个“溢出”错误。 Fortunately, I needed to close the dos console at the end of the batch file.幸运的是,我需要在批处理文件末尾关闭 dos 控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM