LittleNorm
LittleNorm

Reputation: 29

Shell command does not return the correct result

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".

Upvotes: 1

Views: 252

Answers (1)

41686d6564
41686d6564

Reputation: 19661

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

Upvotes: 2

Related Questions