3.4 列出每个可访问商店中每个文件夹的名称

在第 2 部分中,向你展示了如何列出每个商店中的每个可访问商店和顶级文件夹。这涉及到商店的循环,然后通过其文件夹为每个商店循环上面你已经看到如何在文件夹层次结构中的任何深度引用已知文件夹。这包括链接到尽可能多的 Folders("x")s 到达文件夹。

我现在想要在每个商店中列出任何深度的每个文件夹。用于解决此类问题的最简单的编码技术是递归,其中必须向下移动不同长度的链。如果你是另一种语言或工具的认真程序员,你可能已经了解了递归。如果你有成为一名认真的程序员的野心,你将需要最终了解递归,但不一定是今天。 递归是许多人一开始难以理解的概念之一。你可以在你最喜爱的搜索引擎中输入递归,并阅读解释此概念的各种尝试。或者,你可以接受这些宏工作,但不必担心它们如何工作。

请注意 ListStoresAndAllFolders() 中的注释:这些宏需要引用 Microsoft Scripting Runtime。单击 Tools VB Editor 窗口顶部的选项卡栏,然后单击 References。你将获得所有可用引用(库)的列表。顶部的一些已经被勾选。其余部分按字母顺序排列。向下滚动列表,然后单击 Microsoft Scripting Runtime 左侧的框以打勾。然后点击 OK

 Sub ListStoresAndAllFolders()

  ' Displays the name of every accessible store
  ' Under each store, displays an indented list of all its folders

  ' Technique for locating desktop from answer by Kyle:
  ' http://stackoverflow.com/a/17551579/973283

  ' Needs reference to `Microsoft Scripting Runtime` if "TextStream"
  ' and "FileSystemObject" are to be recognised

  Dim FileOut As TextStream
  Dim FldrCrnt As Folder
  Dim Fso As FileSystemObject
  Dim InxFldrCrnt As Long
  Dim InxStoreCrnt As Long
  Dim Path As String
  Dim StoreCrnt As Folder

  Path = CreateObject("WScript.Shell").SpecialFolders("Desktop")
  
  Set Fso = CreateObject("Scripting.FileSystemObject")
  Set FileOut = Fso.CreateTextFile(Path & "\ListStoresAndAllFolders.txt", True)

  With Application.Session
    For InxStoreCrnt = 1 To .Folders.Count
      Set StoreCrnt = .Folders(InxStoreCrnt)
      With StoreCrnt
        FileOut.WriteLine .Name
        For InxFldrCrnt = .Folders.Count To 1 Step -1
          Set FldrCrnt = .Folders(InxFldrCrnt)
          Call ListAllFolders(FldrCrnt, 1, FileOut)
        Next
      End With
    Next
  End With

  FileOut.Close

End Sub
Sub ListAllFolders(ByRef Fldr As Folder, ByVal Level As Long, ByRef FileOut As TextStream)

  ' This routine:
  '  1. Output name of Fldr
  '  2. Calls itself for each child of Fldr
  ' It is designed to be called by ListStoresAndAllFolders()

  Dim InxFldrCrnt As Long

  With Fldr
    FileOut.WriteLine Space(Level * 2) & .Name
    For InxFldrCrnt = .Folders.Count To 1 Step -1
      Call ListAllFolders(.Folders(InxFldrCrnt), Level + 1, FileOut)
    Next
  End With

End Sub

运行 ListStoresAndAllFolders 后,DeskTop 上会有一个名为“ListStoresAndAllFolders.txt”的新文件,其中包含商店和文件夹的承诺列表。