Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enter multiple line of code in CMD from VBA?

Tags:

excel

cmd

vba

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?

like image 406
Dubblej Avatar asked Jan 06 '23 16:01

Dubblej


1 Answers

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

like image 65
Andreas Avatar answered Jan 17 '23 17:01

Andreas