在 Excel VBA 中链接 Do-While 循环时出现问题

Problem when chaining Do-While loops in Excel VBA

我有一个关于 Excel VBA 中的代码的问题,它应该遍历所有(子)文件夹和每个文件夹中的所有 .jpg 文件。这是代码:

Sub list()
'
' list Macro
'
Dim folder
Dim path As String
path = "C:\Users\Lorian\Desktop\Example_jpegALL\"
folder = Dir(path, vbDirectory)

Do While folder <> ""

    Debug.Print folder
    
    Dim file
    Dim path2 As String
    path2 = path & folder & "\"
    file = Dir(path2 & "*.jpg")
    
    Do While file <> ""
    
        Debug.Print file
        file = Dir()
        
    Loop

    folder = Dir()
Loop

End Sub

调试工具告诉我错误来自行“folder = Dir()”,更具体地说是“运行-time error 5 : invalid procedure call or argument”。我对这个错误进行了研究,但没有任何帮助...

更新感谢上面的评论,我能够通过使用集合来更正代码:

Sub list()
'
' list Macro
'
Dim folder
Dim path As String
Dim Coll As New Collection
path = "C:\Users\Lorian\Desktop\Example_jpegALL\"
folder = Dir(path, vbDirectory)


    Do While folder <> ""
    
        Coll.Add folder
        folder = Dir()
        
    Loop



    Dim file
    Dim path2 As String
    
    For Each folder In Coll
    
    Debug.Print folder
    path2 = path & folder & "\"
    file = Dir(path2 & "*.jpg")
    
    Do While file <> ""
    
        Debug.Print file
        file = Dir()
        
    Loop

    Next
End Sub

但是我仍然有一个小错误,由于我无法理解的原因,输出还返回了我桌面上的 JPG 文件,例如这是它给我的输出(前两个文件来自我的桌面, 其余的都是打算):

.
..
91cba94b061174b15ca65010e00edb03.jpg
holyshit.JPG
1
jpegsystems-home.jpg
JPEG_example_flower.jpg
2
jpegxt-home.jpg
3
happy_dog.jpg
images.jpg
téléchargement (1).jpg
téléchargement.jpg
PDF

像这样:

'
' list Macro
'
Sub list()
    Const FPATH As String = "C:\Users\twilliams\OneDrive - Theravance Biopharma\Desktop\pics\"
    Dim d, coll As New Collection, file, f, folder
    
    coll.Add FPATH 'add the root folder
    'check for subfolders (one level only)
    d = Dir(FPATH, vbDirectory)
    Do While d <> ""
        If (GetAttr(FPATH & d) And vbDirectory) <> 0 Then
            If d <> "." And d <> ".." Then coll.Add FPATH & d
        End If
        d = Dir()
    Loop
    
    For Each folder In coll
        Debug.Print "Checking folder"; folder
        file = Dir(folder & "\*.jpg")
        Do While file <> ""
            Debug.Print , file
            file = Dir()
        Loop
    Next
End Sub