如何在VBA中inputCMD中的多行代码?
对于一个小项目,我想要一个macros来打开一个cmd.exe,然后执行几行代码。
我在网上search了一些很好的例子,在那里找不到合适的解决scheme。 我尝试修改的代码如下:
strToPrint = "Hello World!" Shell "cmd.exe /K echo " & strToPrint, vbNormalFocus
我发现这个代码: 如何从VBA写入消息到命令窗口?
对于我的testing,我试图把它变成多行编码,但执行下面的代码后,两行都在不同的命令窗口中执行,请参阅下面的代码:
Sub CMD_VBA_Script() Shell "cmd.exe /K echo Hello World!", vbNormalFocus Shell "cmd.exe /K color 0a", vbNormalFocus End Sub
我明白,当我打电话给shell两次,它会执行两次,但我不知道如何把多行到一个命令窗口。
我的最终目标是从VBA调用以下脚本:
@echo off title Matrix color 0a mode 1000 :a echo %random%%random% goto a
有人能帮助我正确的方向如何从VBA执行多行代码到命令提示符?
问候,杜布莱吉
MyFile = "C:\cmdcode.bat" fnum = FreeFile() Open MyFile For Output As #fnum Print #fnum, "@echo off" Print #fnum, "title Matrix" Print #fnum, "color 0a" Print #fnum, "mode 1000" Print #fnum, "" Print #fnum, ":a" Print #fnum, "echo %random%%random%" Print #fnum, "goto a" Close #fnum ' Run bat-file: Shell MyFile, vbNormalFocus ' optional, remove bat-file: Kill "C:\cmdcode.bat"
所以总之。 你需要创build一个你运行的bat文件。 如果在完成后不需要bat-file,可以使用Kill
删除它
看起来你想要执行一个命令提示符batch file – 批处理是有状态的,所以单独执行每一行不会像执行批处理一样具有相同的效果。
另外两种方法涉及通过指示一个交互式的cmd.exe
实例来执行伪命令,通过一些自动化的过程input命令:发送窗口消息或者inputcmd
进程的stdin
stream。 我不推荐这些方法中的任何一种,因为它们固有的片状(即依赖于无证行为)
所以最好的方法是按照预期的方式执行一个batch file – 您需要先将batch file写入临时文件,然后执行它:
使用这里的代码: https : //support.microsoft.com/en-us/kb/195763
Dim tempFileName As String tempFileName = CreateTempFile("SomeBatch.cmd") WriteToBatchFile( tempFileName ) ' you will have to write to the temp batch file yourself here Shell "cmd.exe /c """ & tempFileName & """", vbHide, True ' Run the batch file, then cmd.exe will terminate. The Shell function will block until cmd is closed Kill tempFile ' delete the temp batch file