Executing a bat file from Excel

R

Roger Govier

Hi

Shell("cmd.exe /c test.bat")

worked fine for me and ran test.bat in C:\Windows\System32
Give the full path of where your file is located
Ensure you have Exit as the last line of your bat file to return back to
Excel
 
M

Mr BT

Thanks to both of you.
I forgot to mention, in order for this to work the way I need it to, I need,
I guess, a sendkeys command for the batch file to hit ENTER twice before it
closes.
Is this possible?

Thanks again

Mr BT
 
R

Roger Govier

Hi Gary
x = Shell("cmd.exe /c C:\testfile.bat", 1)

I have never actually shelled out to CMD to carry out a task before, but
find it interesting
I can see that the x= and the ,1 allows CMD to take the focus.
With mine, which I only tested from the Immediate window, I had to
manually select the CMD window.

Had my bat file been anything other than the simple "Hello world",
Pause, (which did require a user input), I had assumed that it would
have executed and returned focus back to Excel VBE anyway.

Is this correct, or should one always use the format you show?
 
H

Harlan Grove

Gary''s Student said:
I don't know.....maybe a pair of empty echos??? ....

Yup.

"Mr BT" wrote: ....

Macro could be

Sub foo()
Dim x As Variant
x = Shell(Environ("COMSPEC") & _
" /c (echo/&echo/) | ""x:\what\ever.bat""")
End Sub

Peruse the Google Groups archive for the alt.msdos.batch.nt newsgroup
if curious why this particular form for echo is optimal.

Also, FWIW, no exit statement is necessary in the batch file. The
console window will close when the batch file ends. You only need
explicit exit commands when exiting before reaching the end of the
batch file.

Also note that batch files launched this way will run asynchronously,
i.e., the Excel macro that launches it won't wait for the batch file
to end before it continues past the Shell call.
 
G

Gary''s Student

I shell to CMD because its smart enough to know all the file associations.
This means that I can shell to a filename instead of an application as long
as I have set the association corrrectly.

For example, if I open a PDF file and the computer has the full Acrobat
installed the file opens. If only the Reader is installed, the file still
opens, but with just the Reader. Checkout Harlan's comments - they are
valuable,
 
M

Mr BT

empty echos?
Could you explain how I could include this in the vb script?

Thanks

MrBT
 
H

Harlan Grove

Mr BT said:
empty echos?

Console commands that produce only newlines, which when redirected to
the batch file via a pipeline would be processed by the batch file in
exactly the same way as pressing [Enter].

The point is you don't need to use SendKeys from Excel to the console
window. The command that launches the batch file can simulate pressing
[Enter] twice during batch file execution as long as you want fully
NONINTERACTIVE batch file execution.
Could you explain how I could include this in the vb script?

See my previous post.
 
Top