Search code examples
excelvbawscript.shell

How to file filter using wscript.shell when populating with Application.WorksheetFunction.Transpose(files)


Cannot determine the correct parameter to file filter with recursive wscript.shell.

Have tried to filter in Application.FileDialog, failed. Have tried to include .txt extension following dir, failed, still retrieves all files in the recursive directories.

Sub test()
    Rows("5:" & Rows.Count).ClearContents
    Dim fileSpec As String, files As Variant
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = -1 Then
            Folder = .SelectedItems(1)
        Else
            Exit Sub
        End If
    End With
    fileSpec = Folder
    Debug.Print Folder
    ' How to file filter to select only files with a specific *.dbf extension?
    ' How to get the path without the file name and place into another column?
    files = Split(CreateObject("wscript.shell").exec("cmd /c dir " & Chr(34) & fileSpec & Chr(34) & " /b/s ").stdout.readall, vbCrLf)
    ActiveSheet.Range("C5").Resize(UBound(files)).Value = Application.WorksheetFunction.Transpose(files)
End Sub

Solution

  • I added a Dim statement to folder so there was no error on that. Then I added *.TXT to your WSript code. This now only returns Text Files.

    Sub test()
        Rows("5:" & Rows.Count).ClearContents
        Dim fileSpec As String
        Dim files As Variant
        Dim folder As Variant
    
        With Application.FileDialog(msoFileDialogFolderPicker)
            If .Show = -1 Then
                folder = .SelectedItems(1)
            Else
                Exit Sub
            End If
        End With
        fileSpec = folder
        Debug.Print folder
        ' How to file filter to select only files with a specific *.dbf extension?
        ' How to get the path without the file name and place into another column?
        files = Split(CreateObject("wscript.shell").exec("cmd /c dir " & Chr(34) _
                & fileSpec & "\*.txt" & Chr(34) & " /b/s ").StdOut.ReadAll, vbCrLf)
        ActiveSheet.Range("C5").Resize(UBound(files)).Value = _
                Application.WorksheetFunction.Transpose(files)
    End Sub