列出包含关键字

时间:2015-08-01 10:00:16

标签: excel vba dir

我找到了一个列出文件夹所有子文件夹的Excel VBA宏,但我需要的是只列出名称中包含特定关键字的子文件夹。 我真的不知道从哪里开始。这就是我到目前为止所做的:

Sub ShowFolderList2()
    Dim fs, f, f1, fc, s, Keyword As String
    Dim folderspec
    Keyword = "test"
    folderspec = CurDir()
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.SubFolders
    For Each f1 In fc
        s = s & f1.name
        s = s & vbCrLf
    Next
    Debug.Print folderspec
    Debug.Print s
End Sub

我设法使用Dir列出特定扩展名的文件,其名称包含关键字,使用以下脚本:

'EXTENSION TEST
If Extension = "Excel" Then
File1 = Dir(MainPath & Path1 & "*.xl??")
Debug.Print (File1)

ElseIf Extension = "PDF" Then
File1 = Dir(MainPath & Path1 & "*.PDF")
Debug.Print (File1)

ElseIf Extension = "DIR" Then
File1 = Dir(MainPath & Path1 & KeyWord1 & "*", vbDirectory)

'Find path to File1 based on KeyWord1

While (File1 <> "")
   If InStr(File1, KeyWord1) > 0 Then
       'Print File1 path into A column starting in cell 3
       Sheet3.Cells(j + i, 1).Value = Path1 & File1
       i = i + 1
   End If
File1 = Dir
Wend

但是我无法将它们放在一起列出子文件夹/目录。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

Folder库中的FileSystemObject对象包含一个SubFolders集合,您可以使用该集合来迭代给定文件夹的子文件夹。只需检查Folder.Name属性即可确定其名称以及您的关键字是否存在。

Const strPath    As String = "c:\"
Const strKeyword As String = "program"
Dim objSubFolder As Object

With CreateObject("Scripting.FileSystemObject")
    For Each objSubFolder In .GetFolder(strPath).SubFolders
        If InStr(1, objSubFolder.Name, strKeyword, vbTextCompare) > 0 Then
            Debug.Print objSubFolder.Path
        End If
    Next
End With

在我的(64位)机器上打印:

C:\Program Files
C:\Program Files (x86)
C:\ProgramData

答案 1 :(得分:0)

尝试以下操作,根据需要修改常量表达式 - 黑色CMD框会在短时间内出现,这是正常的:

Sub SO()

Const parentDrive As String = "C:\" '// Change as required
Const keyword As String = "myWord" '// Change as required
Dim results As Variant, folder As Variant

results = Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & parentDrive & _
    "*" & keyword & "*"" /B /S /A:D").StdOut.ReadAll, vbCrLf)

For Each folder In results
    Debug.Print folder
Next

End Sub  

这将通过Dir运行cmd.exe命令并读回输出,然后在换行符上拆分输出,以便我们最终得到返回的每个文件夹的数组。

在上面的示例中,命令DIR C:\*myWord* /B /S /A:D通过CMD运行。

  • CMD /C - Shell CMD.exe(以下任何内容作为参数传递 - /C开关告诉Shell方法在执行命令后关闭。)
  • DIR C:\*myWord* - C:\ *myWord*中搜索所有目录的所有电子邮件(请注意*通配符)。
  • /B B asic开关 - 显示结果的基本格式。
  • /S S ubfolder开关 - 在搜索过程中向下钻取所有子文件夹。
  • /A:D ttribute切换 D irectory参数 - 仅返回具有目录(不是文件)属性的结果
相关问题