【VBA】コマンドプロンプトの実行結果を取得する

VBAから
コマンドプロンプトのコマンドを実行して…

コマンドプロンプト(pingコマンド)の実行結果
コマンドプロンプト(pingコマンド)の実行結果


その結果を
VBAで取得できます!

コマンドプロンプト(pingコマンド)の実行結果を取得
コマンドプロンプト(pingコマンド)の実行結果を取得
PR

VBAコード

ここでは例として、
 ・コマンド「ping 192.168.10.1」を実行して
 ・結果を取得
します。
※「pingコマンド」は「ネットワークの疎通確認をするコマンド」です。

'変数の宣言を必須
Option Explicit

Sub sample()

    Dim command As String
    Dim wsh As Object
    Dim execObj As Object
    Dim commandResult As String
    
    '実行するコマンドを指定
    command = "ping 192.168.10.1"
    
    Set wsh = CreateObject("WScript.Shell")
    
    'コマンドを実行
    Set execObj = wsh.exec("%ComSpec% /c " & command)

    'コマンドの実行結果を取得
    commandResult = execObj.stdOut.ReadAll
    
    'コマンドの実行結果を表示
    MsgBox commandResult
    
    '後片付け
    Set execObj = Nothing
    Set wsh = Nothing
    
End Sub

「WScript.Shell」の「exec」メソッドでコマンドを実行します(17行目)。

PR

実行結果

コマンドプロンプトの実行結果を取得できました。

実行結果
実行結果
PR

参考①

シンプルに「コマンドプロンプトのコマンドを実行」することもできます。

詳細は以下の記事をご確認ください。

PR

参考②

上記のVBAコードで使用した以下の詳細は、公式サイトをご確認ください。

●「WScript.Shell」の「exec」メソッド


●「WScript.Shell」の「stdOut」プロパティ

タイトルとURLをコピーしました