不能在 VBA 中从 WScript Shell 运行 DIR?

Can't run DIR from WScript Shell in VBA?

我在很多 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 函数!)来获取与搜索模式匹配的文件列表?

如果您在 dir 命令前加上 "cmd /c " 并将 DOS 命令用双引号引起来,例如

,它是否有效?
RunCmd("cmd /c ""DIR""")

RunCmd("cmd /c ""Dir c:\config* /a:-d /b /d /s""")