开发者

Redirecting input to an executable from Excel VBA

How do you redirect input to an executable from inside VBA? Specifically, why does the code below not work?

ChDir theRightDirectory
Set WshShell = VBA.CreateObject("WScript.Shell") 
WshShell.Run "runme &l开发者_开发技巧t; start.txt", 1, True

Or

RetVal = Shell("runme < start.txt", vbNormalFocus)  

runme.exe does start up all right, but the input is not redirected and has to be type in manually in the command window. Also tried:

RetVal = Shell("type start.txt | runme.exe", vbNormalFocus)

Piping the output of type start.txt into runme.exe just plain returns a “file not found” error.

Yet when I type those various commands directly at the command line, they all work.


Execute the command this way:

WshShell.Run "%COMSPEC% /C runme < start.txt", 1, True

That way it will run it through the command line interpreter.


I've been made aware of this solution: No need to write the input to start.txt; input can just be fed directly to the input stream. (My question should have made clear that this is also an option.) A bonus is that the user can get feedback from the output stream.

Set WshShell = VBA.CreateObject("WScript.Shell")
WshShell.CurrentDirectory = theRightDirectory
Set oExec = WshShell.exec("runme.exe")

' Write to the input stream
oExec.StdIn.Write "some input for the first prompt" & vbCrLf & _
                  "some more input" & vbCrLf 

' The output stream can be shown to the user, e.g.
sOutput = oExec.StdOut.ReadAll()
MsgBox (sOutput)


I'll answer a more general part of your question. You asked:

Specifically, why does the code below not work?

WshShell.Run "runme < start.txt", 1, True

The reason the code does not work as you expect is because the shell of WScript.Shell is not the same as the shell of cmd.exe. In particular, it does not do redirects or pipes.

If you were able to debug the runme process you would see that it has been passed two arguments, < and start.txt

As previously answered, there are two ways to fix this:

  • feed the WScript.Shell StdIn directly and remove your redirect

    set oExec = WshShell.exec(cmdLine)
    oExec.StdIn.Write "some input for the first prompt" & vbCrLf

  • run the DOS shell instead of runme, let it interpret the rest of the commandline, including the redirect

    WshShell.Run "%COMSPEC% /C runme < start.txt", 1, True


You are probably shelling out to a different folder than you expect.

You may have to change directory using CHDIR to the appropriate folder, or qualify your file names using the entire or relative path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜