![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
VBAから
コマンドプロンプトのコマンドを実行して…
![コマンドプロンプト(pingコマンド)の実行結果](https://excel-vba.work/wp-content/uploads/2021/04/vba_getcommandresult_003.png)
![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
その結果を
VBAで取得できます!
![コマンドプロンプト(pingコマンド)の実行結果を取得](https://excel-vba.work/wp-content/uploads/2021/04/vba_getcommandresult_002.png)
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
実行結果
コマンドプロンプトの実行結果を取得できました。
![実行結果](https://excel-vba.work/wp-content/uploads/2021/04/vba_getcommandresult_002.png)
参考①
シンプルに「コマンドプロンプトのコマンドを実行」することもできます。
詳細は以下の記事をご確認ください。
参考②
上記のVBAコードで使用した以下の詳細は、公式サイトをご確認ください。
●「WScript.Shell」の「exec」メソッド
●「WScript.Shell」の「stdOut」プロパティ