使用Excel VBA在命令提示符中执行命令

48
我有一个固定的命令需要使用VBA传递给命令提示符,然后该命令应该运行。例如:"perl a.pl c:\temp"
以下是我正在尝试使用的命令,但它只打开命令提示符,而不运行命令。
请检查: Call Shell("cmd.exe -s:" & "perl a.pl c:\temp", vbNormalFocus)

2
你甚至不需要先打开cmd.exe -> Shell()可以直接将你的perl参数传递给perl.exe。 - Cor_Blimey
1个回答

69

S参数本身不起作用。

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

不妨试试这样做

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

除非您希望在运行此命令时打开一个命令窗口,否则甚至不需要将 "cmd.exe" 添加到此命令中。Shell 应该会自行执行命令。

Shell("perl a.pl c:\temp")



-编辑-
如需等待命令完成,您将需要执行类似于@Nate Hekman在他的答案中所示的操作。

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

6
请记住,当shell启动进程后就会返回。它不会等待你的Perl脚本完成,仅此而已。 - AKDADEVIL
非常感谢。这个运行得很好。等待我的Perl脚本完成的代码是什么? - user1699227
我认为需要做类似于这样的事情 - Ripster
如果我需要从Excel单元格中传递变量之一,而不是固定命令,那么该怎么做呢? 目前,我已经尝试了以下方式(X是变量)wsh.Run "cmd.exe /S /C perl a.pl" & X & "100", windowStyle, waitOnReturn - user1699227
等待命令完成的另一种方法是使用CreateProcessA函数。有关VBA代码,请参阅此Microsoft文章,“确定shell进程何时结束”,https://learn.microsoft.com/en-us/office/vba/access/concepts/windows-api/determine-when-a-shelled-process-ends - scenography

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接