2

I use the following function in a lot of my VBA projects. I initially added the reference to Windows Script Host Object model to take advantage of Intellisense, but then switched to late binding so I didn't have to reference a bunch of stuff.

Private Function RunCMD(ByVal strCMD As String) As String
    'Runs the provided command
    Dim oShell As Object 'New WshShell
    Dim cmd As Object 'WshExec
    Dim x As Integer
    Const WshRunning = 0

    On Error GoTo wshError

    x = 0
    RunCMD = "Error"
    Set oShell = CreateObject("Wscript.Shell")
    Set cmd = oShell.Exec(strCMD)
    'Debug.Print strCMD
    'Stop
    Do While cmd.Status = WshRunning
        Sleep 100 'for 1/10th of a second
        x = x + 1
        If x > 1200 Then 'We've waited 2 minutes so kill it
            cmd.Terminate
            MsgBox "Error: Timed Out", vbCritical, "Timed Out"
        End If
    Loop

    RunCMD = cmd.StdOut.ReadAll & cmd.StdErr.ReadAll
    Set oShell = Nothing
    Set cmd = Nothing
    Exit Function

wshError:
    On Error Resume Next
    RunCMD = cmd.StdErr.ReadAll
    Resume Next
End Function

It works great when you do something like RunCMD("ping www.bing.com") or RunCMD("winrs -r:" & strHost & " reg query hklm\system\currentcontrolset\services\cdrom /v start")

However RunCMD("Dir c:\config* /a:-d /b /d /s") fails, and cmd.StdErr.ReadAll gives an Object Variable or With Block not set error. Even a simple RunCMD("Dir") fails.

Why does DIR make the WScript shell crap out? More importantly, how can I use CMD's DIR function (not VBA's DIR function!) to get a list of files that match a search pattern?

8
  • 1
    This probably doesn't address the primary failure but shouldn't you be piping you output to a TXT file to be opened and manipulated after the operation has completed? Commented Jun 14, 2016 at 21:08
  • 1
    Have you tried it with Set oShell = CreateObject("Cscript.Shell") ? Commented Jun 14, 2016 at 21:10
  • it's actually giving the error The system cannot find the file specified. Commented Jun 14, 2016 at 21:44
  • Do you need to use command line tools/is this just and example? or Can you use the FileSystemObject which can do this much much nicer. Commented Jun 14, 2016 at 21:44
  • Along with @Brad comment, VBA has DIR command as well. Commented Jun 14, 2016 at 21:50

1 Answer 1

3

Does it work if you preface your dir command with "cmd /c " and wrap your DOS command in double quotes, like

RunCmd("cmd /c ""DIR""")

or

RunCmd("cmd /c ""Dir c:\config* /a:-d /b /d /s""")
Sign up to request clarification or add additional context in comments.

2 Comments

@Robin - and there's the reasoning. Excellent!

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.