我在很多VBA项目中使用以下函数。我最初添加了对Windows脚本宿主对象模型的引用以利用Intellisense,但随后切换到后期绑定,因此我不必引用一堆东西。
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
当你做类似的事情时,效果很好
RunCMD("ping www.bing.com")
或
RunCMD("winrs -r:" & strHost & " reg query hklm\system\currentcontrolset\services\cdrom /v start")
但是RunCMD("Dir c:\config* /a:-d /b /d /s")
失败,cmd.StdErr.ReadAll
给出了对象变量或者没有设置块错误。即使是简单的RunCMD("Dir")
也会失败。
为什么DIR会让WScript shell崩溃?更重要的是,我如何使用CMD的DIR功能(不是VBA的DIR功能!)来获取与搜索模式匹配的文件列表?
答案 0 :(得分:3)
如果你在dir命令前加上" cmd / c"它是否有用并用双引号括起DOS命令,如
RunCmd("cmd /c ""DIR""")
或
RunCmd("cmd /c ""Dir c:\config* /a:-d /b /d /s""")