【问题标题】:Can't run DIR from WScript Shell in VBA?无法在 VBA 中从 WScript Shell 运行 DIR?
【发布时间】:2016-06-14 21:03:33
【问题描述】:

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

【问题讨论】:

  • 这可能无法解决主要故障,但您不应该将输出传输到 TXT 文件以在操作完成后打开和操作吗?
  • 你用Set oShell = CreateObject("Cscript.Shell")试过了吗?
  • 它实际上给出了错误The system cannot find the file specified.
  • 您是否需要使用命令行工具/这只是示例吗?或者你能不能使用 FileSystemObject 做得更好。
  • 除了@Brad 评论,还有VBA has DIR 命令。

标签: vba shell excel wsh


【解决方案1】:

如果您在 dir 命令前加上“cmd /c”并将您的 DOS 命令用双引号括起来,它是否有效,例如

RunCmd("cmd /c ""DIR""")

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 2022-06-18
相关资源
最近更新 更多