Kann DIR nicht über die WScript-Shell in VBA ausgeführt werden?
In vielen meiner VBA-Projekte verwende ich die folgende Funktion. Ich habe zunächst den Verweis auf das Windows Script Host Object-Modell hinzugefügt, um die Vorteile von Intellisense zu nutzen, dann aber auf die späte Bindung umgestellt, damit ich nicht auf einige Dinge verweisen musste.
Private Function RunCMD(ByVal strCMD As String) As String
'Runs the provided command
Dim oShell As Object 'New WshShell
Dim cmd As Object 'WshExec
Dim x As Integer
Const WshRunning = 0
On Error GoTo wshError
x = 0
RunCMD = "Error"
Set oShell = CreateObject("Wscript.Shell")
Set cmd = oShell.Exec(strCMD)
'Debug.Print strCMD
'Stop
Do While cmd.Status = WshRunning
Sleep 100 'for 1/10th of a second
x = x + 1
If x > 1200 Then 'We've waited 2 minutes so kill it
cmd.Terminate
MsgBox "Error: Timed Out", vbCritical, "Timed Out"
End If
Loop
RunCMD = cmd.StdOut.ReadAll & cmd.StdErr.ReadAll
Set oShell = Nothing
Set cmd = Nothing
Exit Function
wshError:
On Error Resume Next
RunCMD = cmd.StdErr.ReadAll
Resume Next
End Function
Es funktioniert gut, wenn Sie so etwas wie @ tRunCMD("ping www.bing.com")
oderRunCMD("winrs -r:" & strHost & " reg query hklm\system\currentcontrolset\services\cdrom /v start")
JedochRunCMD("Dir c:\config* /a:-d /b /d /s")
schlägt fehl undcmd.StdErr.ReadAll
gibt eine Objektvariable an oder With Block not set error. Sogar ein einfachesRunCMD("Dir")
schlägt fehl.
Warum macht DIR die WScript-Shell kaputt? Was noch wichtiger ist, wie kann ich die DIR-Funktion von CMD (nicht die DIR-Funktion von VBA!) Verwenden, um eine Liste von Dateien zu erhalten, die einem Suchmuster entsprechen?