つらつら Excel VBA

私の備忘録です。

コマンド実行結果を受け取る

PowerShellも同じやり方。渡すテキスト変えるだけ。
コマンドにオプション付けたり、Splitなどを使って結果を取捨選択してください。

Sub コマンドプロンプト()
    
    Dim WSH, wshExec, sCmd As String, sResult As String
    
    Set WSH = CreateObject("WScript.Shell")
    
    'コマンドプロンプト
    sCmd = "dir C:\"
    Set wshExec = WSH.Exec("%ComSpec% /c " & sCmd)
    
'    'PowerShell
'    sCmd = "Get-ChildItem C:\"
'    Set wshExec = WSH.Exec("powershell " & sCmd)
    
    Do While wshExec.Status = 0
        DoEvents
    Loop
    
    sResult = wshExec.StdOut.ReadAll
    Debug.Print sResult
    
    Set wshExec = Nothing
    Set WSH = Nothing
    
End Sub

以上。