列出包含关键字的所有子文件夹

我发现一个Excel VBAmacros列出了一个文件夹的所有子文件夹,但是我需要的是只列出在其名称中包含特定关键字的子文件夹。 我不知道从哪里开始。 这是我迄今为止:

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 

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

FileSystemObject库中的Folder对象包含一个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 

尝试以下操作,根据需要修改常量expression式 – 黑色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 

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

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

  • CMD /CShell CMD.exe(以下任何内容都作为parameter passing – /C开关指示执行命令后,Shell方法closures)。
  • DIR C:\*myWord* myWord DIR C:\*myWord*searchC:\ myWord DIR C:\*myWord* 所有目录 (注意*通配符)。
  • /B基本开关 – 显示结果的基本格式。
  • /S S ubfolder开关 – 在search过程中向下search所有子文件夹。
  • /A:D采用D irectory参数的ttribute开关 – 仅返回具有作为目录(不是文件)属性的结果。