将输入从 Excel VBA 重定向到可执行文件 [英] Redirecting input to an executable from Excel VBA

查看:28
本文介绍了将输入从 Excel VBA 重定向到可执行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 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 < start.txt", 1, True

或者

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

runme.exe 确实可以正常启动,但输入没有重定向,必须在命令窗口中手动输入.也试过了:

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)

type start.txt 的输出传送到 runme.exe 中,只会返回找不到文件"错误.

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'll answer a more general part of your question. You asked:

具体来说,为什么下面的代码不起作用?

WshShell.Run "runme

Specifically, why does the code below not work?

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

代码没有按预期工作的原因是 WScript.Shell 的外壳与 cmd.exe 的外壳不同.特别是,它不进行重定向或管道.

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.

如果您能够调试 runme 进程,您会看到它传递了两个参数,<start.txt

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:

  • 直接输入 WScript.Shell StdIn 并移除重定向

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

set oExec = WshShell.exec(cmdLine)
oExec.StdIn.Write第一个提示的一些输入"&vbCrLf

运行 DOS shell 而不是 runme,让它解释命令行的其余部分,包括重定向

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

WshShell.Run "%COMSPEC%/C runme

这篇关于将输入从 Excel VBA 重定向到可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆