IPアドレスのリストにpingを発行し、結果を表示

IPアドレスのリストに対してpingを発行します。ホスト名、物理アドレス(MACアドレス)も取得。
PingList.xlsmといったファイルを作成し、この中にVBAを組み込みます。
ボタンを作って、PingListMainを呼び出す形でも大丈夫です。

結果は新しいBookを作成して、そこに結果を出力します。

以下の関数を使用していますので、リンクから関数をコピーします。
Pingの実行 PingCommand()
IPアドレスからホスト名を取得する(nslookup) GetHostname()
IPアドレスからMACアドレスを取得する(arp) GetMacAddr()
最終行取得(空白まで) GetBlankRow()

' Pingリスト作成のメイン処理
Sub PingListMain(Optional ws As Worksheet = Nothing)
	Dim last_row As Long
	Dim idx1 As Long
	Dim out_wb As Workbook
	Dim out_ws As Worksheet
	Dim title_data As Variant
	Dim addresslist() As String
	Dim ping_result() As Long

	If ws Is Nothing Then
		Set ws = ActiveSheet
	End If

	' 出力先のタイトルと幅を設定
	title_data = Array(Array("IPアドレス", 20), _
			Array("結果", 40), _
			Array("取得日時", 20), _
			Array("ホスト名", 40), _
			Array("物理アドレス", 20))

	' 最終行を取得(空白まで)
	last_row = GetBlankRow(ws)

	' 領域の確保
	ReDim addresslist(last_row)
	ReDim ping_result(last_row)

	' 出力先 Book を作成
	Set out_wb = Workbooks.Add
	' 出力先 Sheet を作成
	Set out_ws = out_wb.Sheets(1)

	' 出力先のタイトルと幅を設定
	For idx1 = 0 To UBound(title_data)
		out_ws.Cells(1, idx1 + 1) = title_data(idx1)(0)
		out_ws.Columns(idx1 + 1).ColumnWidth = title_data(idx1)(1)
	Next idx1

	' pingを発行して情報を取得(タイトル分 -1 します)
	For idx1 = 1 To last_row - 1
		' リストの読み込み(シート側は、タイトルが含まれているので+1)
		addresslist(idx1) = ws.Cells(idx1 + 1, 1)
		ping_result(idx1) = PingCommand(addresslist(idx1))

		' A列に IPアドレス
		out_ws.Cells(idx1 + 1, 1) = addresslist(idx1)

		' B列に 結果
		out_ws.Cells(idx1 + 1, 2) = PingResult(ping_result(idx1))

		' C列に 取得日時
		out_ws.Cells(idx1 + 1, 3) = Now()
		out_ws.Cells(idx1 + 1, 3).NumberFormatLocal = "yyyy/m/d h:mm:ss"

		' ping が成功したアドレスに対してはホスト名を取得する
		If ping_result(idx1) = 0 Then
			' D列に ホスト名
			out_ws.Cells(idx1 + 1, 4) = GetHostname(addresslist(idx1))
			' E列に 物理アドレス
			out_ws.Cells(idx1 + 1, 5) = GetMacAddr(addresslist(idx1))
		End If

		' 他のイベントを処理できるように、実行を渡します
		DoEvents
	Next idx1

	' 確保した領域の解放
	Erase addresslist
	Erase ping_result
End Sub

【補足】
アンチウィルスの種類によっては、スクリプト実行時に処理をブロックすることがあります。
Norton360 アンチウィルスの例は、次を参照してください。
スクリプト実行時の確認(アンチウィルス)

コメント