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 < 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.
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.
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.I'll answer a more general part of your question. You asked:
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,
<
andstart.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
Execute the command this way:
That way it will run it through the command line interpreter.