wrote :: 2006.01.08
Sub Sample1()
Dim WSH, wExec, sCmd As String, Result As String
Set WSH = CreateObject("WScript.Shell") ''(1)
sCmd = "dir C:\" ''(2)
Set wExec = WSH.Exec("%ComSpec% /c " & sCmd) ''(3)
Do While wExec.Status = 0 ''(4)
DoEvents
Loop
Result = wExec.StdOut.ReadAll ''(5)
MsgBox Result
Set wExec = Nothing
Set WSH = Nothing
End Sub
(1)でWSHへの参照を作ります。(2)が実行するMS-DOSコマンドです。引数まで指定してください。(3)でExecメソッドを実行しています。コマンドシェルは9x系と2000系で異なりますので%ComSpec%で自動判定させています。実行するとWshScriptExecオブジェクトを返しますので、変数に格納します。MS-DOSコマンドは完了まで時間がかかることがありますので(4)のようにループで完了を待ちます。完了したかどうかはWshScriptExecオブジェクトのStatusプロパティで判定します。MS-DOSコマンドの標準出力はStdOutプロパティで取得できますので、すべてを変数Resultに格納しました。最後にオブジェクト変数を解放しておしまいです。
Sub Sample2()
Dim WSH, wExec, sCmd As String, Result As String, tmp, i As Long
Set WSH = CreateObject("WScript.Shell")
sCmd = "dir C:\ /b /aD-H /o-N"
Set wExec = WSH.Exec("%ComSpec% /c " & sCmd)
Do While wExec.Status = 0
DoEvents
Loop
Result = wExec.StdOut.ReadAll
tmp = Split(Result, vbCrLf)
For i = 0 To UBound(tmp)
Cells(i + 1, 1) = tmp(i)
Next i
Set wExec = Nothing
Set WSH = Nothing
End Sub

Sub Sample3()
Dim WSH, wExec, sCmd As String, Result As String, tmp, buf As String, i As Long
Set WSH = CreateObject("WScript.Shell")
sCmd = "tree C:\tmp"
Set wExec = WSH.Exec("%ComSpec% /c " & sCmd)
Do While wExec.Status = 0
DoEvents
Loop
Result = wExec.StdOut.ReadAll
tmp = Split(Result, vbCrLf)
For i = 2 To UBound(tmp) ''3行目以降を変数に格納します
buf = buf & tmp(i) & vbCrLf
Next i
MsgBox buf
Set wExec = Nothing
Set WSH = Nothing
End Sub

Sub Sample4()
Dim WSH, wExec, sCmd As String, Result As String, tmp, buf As String, i As Long
Set WSH = CreateObject("WScript.Shell")
sCmd = "nslookup www.yahoo.co.jp"
Set wExec = WSH.Exec("%ComSpec% /c " & sCmd)
Do While wExec.Status = 0
DoEvents
Loop
Result = wExec.StdOut.ReadAll
tmp = Split(Result, vbCrLf)
For i = 0 To UBound(tmp)
If Left(tmp(i), 5) = "Name:" Then
buf = tmp(i) & vbCrLf & tmp(i + 1)
End If
Next i
MsgBox buf
Set wExec = Nothing
Set WSH = Nothing
End Sub
