Redirecting input to an executable from Excel VBA

2020-01-29 12:49发布

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.

4条回答
We Are One
2楼-- · 2020-01-29 13:05

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)
查看更多
够拽才男人
3楼-- · 2020-01-29 13:07

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.

查看更多
Rolldiameter
4楼-- · 2020-01-29 13:17

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

查看更多
干净又极端
5楼-- · 2020-01-29 13:27

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.

查看更多
登录 后发表回答