首页 > 解决方案 > VBA:如何将此 cmd 命令转换为 VBA Shell 代码

问题描述

我想在 VBA 代码中使用下面的命令行,命令是递归地获取所有 .pdf 和 .docx 文件并在 CMD 中运行得很好

dir /s *.pdf *.docx

现在在 VBA 中,具有以下内容,它以递归方式打印出所有文件,而不是指定的扩展名

Sub Run()
    Debug.Print ShellRun("cmd.exe /c dir c:\ /s *.pdf *.docx")
End Sub

Public Function ShellRun(sCmd As String) As String
    Dim oShell As Object
    Set oShell = CreateObject("WScript.Shell")
    Dim oExec As Object
    Dim oOutput As Object
    Set oExec = oShell.Exec(sCmd)

    ShellRun = oExec.StdOut.ReadAll
End Function

标签: excelvba

解决方案


尝试这个

Debug.Print ShellRun("cmd.exe /c dir /s c:\*.pdf c:\*.docx")

编辑:以下评论

您需要dir /s PATH\*.pdf PATH\*.docx\*. pdf和docx也PATH应该重复。但是,在您的代码中,您有空格,并且您的位置c:\和标志也/s交换了。


推荐阅读