1

In my program I want to do the following command:

RetVal = Shell("dir > temp", 1)

When I do that I get the following error:

Run-time error "53": File not found.

Just doing Shell("dir", 1) gives me the same error. However, if I do Shell("help", 1), it works.

The dir > temp command works fine in the command window. I tried using Shell with the following commands: dir, cd, ver, time, date, help. The only one of these that works is help.

I expect to get a directory listing when I do Shell("dir > temp", 1) that I can do other things with temp. Instead, I get "File not found".

1
  • Assuming (dangerously) that you really mean dir > temp, you may want to specify a full path for temp. Where the file ends up when running from a command prompt may be different than where it ends up when being executed by your VBA code. It never hurts to be fully explicit. Commented Jul 15, 2019 at 17:31

1 Answer 1

2

Not all commands passed to the Shell function will work as it does in the Command Prompt window. The Shell function is meant to run an executable file, not execute commands:

Runs an executable program and returns a Variant (Double) representing the program's task ID if successful; otherwise, it returns zero.

Think about it like the "Run" utility in Windows.

What you should do is call "cmd.exe" first and pass whatever arguments/commands you need to it. Try something like this:

Dim myCommand As String
myCommand = "dir"
Shell "cmd.exe /S /K" & myCommand, vbNormalFocus

If you want the Command Prompt window to close after executing the command, you can replace the parameter /K with /C. In that case, you might also want to use vbHide instead of vbNormalFocus:

myCommand = "dir > temp"
Shell "cmd.exe /S /C" & myCommand, vbHide
Sign up to request clarification or add additional context in comments.

4 Comments

Or simply, Shell "cmd.exe /S /K" & myCommand, vbNormalFocus - unless you also do Call MsgBox("message") and Call Beep and Call DoEvents.
@MathieuGuindon I don't :-) The OP just used braces in their examples so I didn't want to confuse him/her. After a second thought, Call in itself could be more confusing, so you're right! Also, I just noticed that he/she assigns the returned value to a variable so braces should work anyway.
Nah, I just have this particular thing with Call never being used consistently by anyone that ever uses it ;-)
@MathieuGuindon That's a very informative answer. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.