Home > OS >  Problem when chaining Do-While loops in Excel VBA
Problem when chaining Do-While loops in Excel VBA

Time:01-12

I have a problem regarding a code in Excel VBA that should go through all (sub-)folders and through all .jpg files in each folder. Here is the code :

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

The debug tool tells me the error comes from the line "folder = Dir()",more specifically it says "Run-time error 5 : invalid procedure call or argument". I made researchs about this error, but nothing really helped...

UPDATE Thanks to above comments I was able to correct the code by using a collection :

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

However I still have a slight bug, for reasons I can't understand, the output also returned JPG file that are on my desktop, for example here's the output it gives me (the two first file are from my desktop, the rest are intended) :

.
..
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

CodePudding user response:

Like this:

'
' 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
  •  Tags:  
  • Related