AliAlnuaimi
AliAlnuaimi

Reputation: 11

VBA: How to translate this cmd command to VBA Shell Code

I want to use the below Command-line in VBA Code, the command is to get all .pdf and .docx files recursively and runs just fine in CMD

dir /s *.pdf *.docx

Now In VBA, have the below, which is printing out ALL files recursively and not the specified extensions

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

Upvotes: 1

Views: 227

Answers (1)

Super Symmetry
Super Symmetry

Reputation: 2875

Try this

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

Edit: Following comment

You need to run dir /s PATH\*.pdf PATH\*.docx no space between \*. Also PATH should be repeated for both pdf and docx. However, in your code you had spaces and you also had the positions of c:\ and the flag /s swapped.

Upvotes: 2

Related Questions