ExcelのVBA(マクロ)で、tracertコマンドを実行する方法についてまとめました。
tracertコマンドを実行
Excel/VBAでは、WSH(Windows Scripting Host)を実行できます。
今回はこれを利用して「tracertコマンド」を実行してみます。
サンプルコード
サンプルプログラムのソースコードです。
Function tracert(j As Integer, ip As String)
Dim WSH, wExec, cmd As String, Result As String
Dim i As Integer
i = 0
Set WSH = CreateObject("WScript.Shell")
' 実行したいDOSコマンド
cmd = "tracert " & ip
' DOSコマンドを実行
Set exec = WSH.exec("%ComSpec% /c " & cmd)
' DOSコマンドが終了するまで待機
Do While exec.Status = 0
DoEvents
Loop
' DOSコマンドの実行結果(標準出力)を取得
Result = exec.StdOut.ReadAll
' 実行結果を行毎に区切る
tmp = Split(Result, vbCrLf)
For n = 0 To UBound(tmp)
buf = tmp(n) & vbCrLf
' 時間が記載されている行だけセルに挿入
If InStr(buf, "ms") Then
Cells(i + 2, j) = buf
i = i + 1
End If
Next n
' オブジェクトを空に
Set wExec = Nothing
Set WSH = Nothing
End Function
Sub test()
Dim ip As String
Dim j As Integer
Dim jn As Integer
' 列の最大数(IPアドレスの数)を取得
jn = Cells(1, 1).End(xlToRight).Column
' ipの数だけtracertコマンドを実行
For j = 1 To jn Step 1
ip = Cells(1, j).Value
Call tracert(j, ip)
Next j
End Sub
実行結果
サンプルプログラムの実行結果です。
「A1」「B1」…セルのipアドレスに対してtracertコマンドを実行していきます。
そして、ホップ毎の結果をipアドレスの下に記載していきます。
| – | A | B |
|---|---|---|
| 1 | 192.168.100.1 | 192.168.100.1 |
| 2 | 1 3 ms 2 ms 3 ms [192.168.100.1] | 1 3 ms 3 ms 3 ms [192.168.100.1] |
| — | 関連記事 |
|---|---|
| 1 | 【Excel/VBA】マクロ入門 |

コメント