Execute a command in command prompt using excel VB

2019-01-04 10:32发布

I have a fixed command which i need to pass to command prompt using VBA and then the command should run. e.g. "perl a.pl c:\temp"

following is the command i am trying to use but it just opens command prompt and doesn't run the command.

Call Shell("cmd.exe -s:" & "perl a.pl c:\temp", vbNormalFocus)

Please check.

1条回答
叼着烟拽天下
2楼-- · 2019-01-04 10:50

The S parameter does not do anything on its own.

/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  

Try something like this instead

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

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

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



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

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
查看更多
登录 后发表回答