如何在使用Application.WorksheetFunction.Transpose(files)填充时使用wscript.shell进行文件过滤

时间:2019-04-09 06:30:54

标签: excel vba wscript.shell

无法确定使用递归wscript.shell进行文件过滤的正确参数。

尝试在Application.FileDialog中进行过滤,失败。 尝试在dir之后包含.txt扩展名,但失败,仍会检索递归目录中的所有文件。

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

1 个答案:

答案 0 :(得分:1)

我在Dim上添加了folder语句,因此没有错误。然后,我在您的WSript代码中添加了*.TXT。现在,这仅返回文本文件。

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