Capture output value from a shell command in VBA? Capture output value from a shell command in VBA? vba vba

Capture output value from a shell command in VBA?


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 = sEnd Function

Usage:

MsgBox ShellRun("dir c:\")


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","")


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