Found this function http://www.cpearson.com/excel/ShellAndWait.aspx

But would need also to capture output from the shell output. Any code suggestion ?

up vote 20 down vote accepted

You can CreateProcess the application redirecting its StdOut to a pipe, then read that pipe directly; http://pastebin.com/CszKUpNS

dim resp as string 
resp = redirect("cmd","/c dir")
resp = redirect("ipconfig","")
  • Wow couldn't have created this myself thanks :) – user310291 May 8 '10 at 6:51
  • Sorry, but how did you get your code to run? I am trying to do something similar (pull stdout data in to VBA, and I am running on OSX) and I am not sure where to declare your functions. I tried putting them in the same folder that defines the functionality of my user forms when they click submit, but it gave me an error stating "Compile Error: Only comments may appear after End Sub, End Function, or End Property". – Engineero Jun 12 '13 at 1:51
  • 1
    This is Windows specific code as it uses the Windows API; it wont run on OSX no matter what you do - better to ask a new question. – Alex K. Jun 12 '13 at 10:11
  • 1
    CreateProcess() must be called using "ByVal 0&", otherwise e.g. nslookup will not work: lngResult = CreateProcess(0&, szFullCommand, tSA_CreateProcessPrc, tSA_CreateProcessThrd, True, 0&, ByVal 0&, vbNullString, tStartupInfo, tSA_CreateProcessPrcInfo) – user2726485 Aug 28 '13 at 17:48
  • @Martin: Thanks! I was unable to connect to the server (unable to resolve host) due to that exact reason. I updated the "pastebin" code: pastebin.com/w9zzNK4N – lepe Oct 29 '13 at 2:55

Based on Andrew Lessard's answer, here's a function to run a command and return the output as a string -

Public Function ShellRun(sCmd As String) As String

    'Run a shell command, returning the output as a string

    Dim oShell As Object
    Set oShell = CreateObject("WScript.Shell")

    'run command
    Dim oExec As Object
    Dim oOutput As Object
    Set oExec = oShell.Exec(sCmd)
    Set oOutput = oExec.StdOut

    'handle the results as they are written to and read from the StdOut object
    Dim s As String
    Dim sLine As String
    While Not oOutput.AtEndOfStream
        sLine = oOutput.ReadLine
        If sLine <> "" Then s = s & sLine & vbCrLf
    Wend

    ShellRun = s

End Function

Usage:

MsgBox ShellRun("dir c:\")
  • 1
    I credited this great answer of yours on a recent Python post. Feel free to answer it directly and I will delete my own. – Parfait Sep 15 '16 at 18:11
  • I couldn't get this to work using your example. I needed ShellRun("cmd.exe /c dir c:\") instead. Then it worked perfectly. Thank you. – mal Sep 16 '16 at 3:21
  • 4
    you don't need the while loop here, you can replace from the line Set oOutput = oExec.StdOut until the end of the function with this line: ShellRun = oExec.StdOut.ReadAll – Pupa Rebbe Jun 6 '17 at 20:02
  • 1
    Also if you need individual lines then you can ShellRun = Split(oExec.StdOut.ReadAll, vbCrLf), and change the function declaration to Public Function ShellRun(sCmd As String) As String(). This gives a 0 indexed array of strings. – Greedo Aug 15 '17 at 17:15
  • Thanks for this - I've been scratching by brain for hours trying to find a solution to get the return from a powershell command. Is there anyway to change the Shell so that it is hidden from view? – Tom Jan 11 at 10:15

You could always redirect the shell output to a file, then read the output from the file.

Sub StdOutTest()
    Dim objShell As Object
    Dim objWshScriptExec As Object
    Dim objStdOut As Object
    Dim rline As String
    Dim strline As String

    Set objShell = CreateObject("WScript.Shell")
    Set objWshScriptExec = objShell.Exec("c:\temp\batfile.bat")
    Set objStdOut = objWshScriptExec.StdOut

    While Not objStdOut.AtEndOfStream
        rline = objStdOut.ReadLine
        If rline <> "" Then strline = strline & vbCrLf & CStr(Now) & ":" & Chr(9) & rline
       ' you can handle the results as they are written to and subsequently read from the StdOut object
    Wend
    MsgBox strline
    'batfile.bat
    'ping 1.1.1.1 -n 1 -w 2000 > nul
    'echo 2
    'ping 1.1.1.1 -n 1 -w 2000 > nul
    'echo 4
    'ping 1.1.1.1 -n 1 -w 2000 > nul
    'echo 6
    'ping 1.1.1.1 -n 1 -w 2000 > nul
    'echo 8
End Sub

Based on bburns.km's answer, I added passing input (using StdInput) to the executable during call. Just in case somebody stumbles upon this and has the same need.

''' <summary>
'''   Executes the given executable in a shell instance and returns the output produced
'''   by it. If iStdInput is given, it is passed to the executable during execution.
'''   Note: You must make sure to correctly enclose the executable path or any given
'''         arguments in quotes if they contain spaces.
''' </summary>
''' <param name="iExecutablePath">
'''   The full path to the executable (and its parameters). This string is passed to the
'''   shell unaltered, so be sure to enclose paths and parameters containing spaces
'''   in quotes (").
''' </param>
''' <param name="iStdInput">
'''   The (optional) input to pass to the executable. Default: Null
''' </param>
Public Function ExecuteAndReturnStdOutput(ByVal iExecutablePath As String, _
                                       Optional ByVal iStdInput As String = vbNullString) _
                As String

   Dim strResult As String

   Dim oShell As WshShell
   Set oShell = New WshShell

   Dim oExec As WshExec
   Set oExec = oShell.Exec(iExecutablePath)

   If iStdInput <> vbNullString Then
      oExec.StdIn.Write iStdInput
      oExec.StdIn.Close    ' Close input stream to prevent deadlock
   End If

   strResult = oExec.StdOut.ReadAll
   oExec.Terminate

   ExecuteAndReturnStdOutput = strResult

End Function

Note: You will need to add a reference to Windows Script Host Object Model so the types WshShell and WshExec are known.
(To do this go to Extras -> References in the VBA IDE's menu bar.)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.