VBA:来自一个 cmd.exe 的多个命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19169918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:38:39  来源:igfitidea点击:

VBA: Multiple commands from one cmd.exe

excelvbaexcel-vba

提问by Michal Korta

I am trying to run VBA script that will execute particular shell program with arguments retrieved from Excel Spreadsheet.

我正在尝试运行 VBA 脚本,该脚本将使用从 Excel 电子表格检索的参数执行特定的 shell 程序。

I'd like to exeute the command n times for n rows in spredsheet, yet have it all in one cmd.exe window. Is that achievable?

我想对 spredsheet 中的 n 行执行 n 次命令,但将其全部放在一个 cmd.exe 窗口中。这是可以实现的吗?

I am doing such steps:

我正在做这样的步骤:

1.Creating shell object:

1.创建shell对象:

Set wsh = VBA.CreateObject("WScript.Shell")

2.Iterating trough all rows in Spreadsheet and calling for each:

2.遍历电子表格中的所有行并调用每个:

wsh.Run("Command with row specific args", 1, true)

As the result I have n console windows opened for n processed rows. Is there any way to avoid it?

结果,我为 n 个处理的行打开了 n 个控制台窗口。有什么办法可以避免吗?

Help appreciated.

帮助表示赞赏。

采纳答案by Mathieu Guindon

You don't give much details, but a solution could be to build a batch (.bat) file (no different from writing to any other text file) with all the parameters you need, save it somewhere and then run it in a single call to cmd.exe. And then you can just delete that file.

您没有提供太多细节,但解决方案可能是使用您需要的所有参数构建一个批处理 (.bat) 文件(与写入任何其他文本文件没有区别),将其保存在某处,然后在单个文件中运行调用cmd.exe。然后你就可以删除那个文件了。



Start with opening the file for output:

首先打开文件进行输出:

Dim fn As Long
fn = FreeFile
Open "filename.bat" For Output As #fn

Then iterate your range, and instead of launching a cmd.exe for each, write to your open file:

然后迭代您的范围,而不是为每个启动一个 cmd.exe,而是写入您打开的文件:

Print #fn "command with row specific args"

Then close your file and run it:

然后关闭您的文件并运行它:

Close #fn
Set wsh = VBA.CreateObject("WScript.Shell")
wsh.Run("filename.bat", 1, true)

Then you can discard the file:

然后你可以丢弃文件:

Kill "filename.bat"