I want to open a cmd.exe and then execute a few lines of code.
I searched the web for some examples.
Code I tried modifying:
strToPrint = "Hello World!"
Shell "cmd.exe /K echo " & strToPrint, vbNormalFocus
I found How to write message to command window from VBA?
I tried multiple lines of coding, but the lines are executed in different command windows:
Sub CMD_VBA_Script()
Shell "cmd.exe /K echo Hello World!", vbNormalFocus
Shell "cmd.exe /K color 0a", vbNormalFocus
End Sub
I understand when I call the Shell two times, that it will execute two times.
My goal is to call the following script from VBA:
@echo off
title Matrix
color 0a
mode 1000
:a
echo %random%%random%
goto a
How can I execute multiple lines of code from VBA in command prompt?
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"
So in short. You need to create a bat-file that you run.
If you don't need the bat-file after it's done you can delete it with Kill
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With