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”的新檔案,其中包含商店和資料夾的承諾列表。