下面是一个示例代码。它遍历给定目录的所有子目录,并在即时窗口中打印目录和文件名。问题是程序如何在本行内自行调用“TraversePath”TraversePath path & directory &“\”“? 。这是递归..那么有没有更好的方法来编码?因为除非我们在正确的上下文中使用递归,否则总会有溢出的机会。如何在不递归的情况下编写这个VBA程序
Sub TraversePath(path As String)
Dim currentPath As String, directory As Variant
Dim dirCollection As Collection
Set dirCollection = New Collection
currentPath = Dir(path, vbDirectory)
'Explore current directory
Do Until currentPath = vbNullString
Debug.Print currentPath
If Left(currentPath, 1) <> "." And _
(GetAttr(path & currentPath) And vbDirectory) = vbDirectory Then
dirCollection.Add currentPath
End If
currentPath = Dir()
Loop
'Explore subsequent directories
For Each directory In dirCollection
Debug.Print "---SubDirectory: " & directory & "---"
'How program is calling/executing below line of code
TraversePath path & directory & "\"
Next directory
End Sub
Sub Testprogram()
TraversePath "D:\VBA\"
End Sub
这是递归。它是计算机科学的标准工具。遍历树是一个常见的用例。请参阅https://en.wikipedia.org/wiki/Recursion_(computer_science) –