Home > Back-end >  Index enters the For Loop despite exceeding the upper limit
Index enters the For Loop despite exceeding the upper limit

Time:03-15

I can't figure out why is the index of my For-Loop entering the loop, despite its value exceeding the upper limit. Please see the pic attached below for clarity.

Dim cnt
cnt = 0  
Debug.Print "Total File Count before entering loop: " & xFolder.Files.Count

For Each oxFile In xFolder.Files
    If Left(oxFile.Name, 1) <> "~" And LCase(oxFile.Name) <> "thumbs.db" Then
        cnt = cnt   1
        Debug.Print "Files processed in each iteration:" & cnt
        Call FixFileNames(oxFile)  'This sub merely shortens the file name.
    End If
Next oxFile


Private Sub FixFileNames(ByRef myFile As Object)
    Dim PrevName As String
    PrevName = myFile.Name
    PrevName = Trim(Replace(PrevName, "_XXXXX_", "", 1)
    myFile.Name = PrevName
End Sub

enter image description here

CodePudding user response:

You can collect all the files before processing them, so there's no chance you'll pick up any new files.

Eg:

Dim cnt, col As New Collection
  
For Each oxFile In xFolder.Files 'collect the files first
    col.Add oxFile
Next oxFile

Debug.Print "Total File Count before entering loop: " & col.Count
cnt = 0
For Each oxFile In col
    If Left(oxFile.Name, 1) <> "~" And LCase(oxFile.Name) <> "thumbs.db" Then
        cnt = cnt   1
        Debug.Print cnt, oxFile.Name
        FixFileNames oxFile  'Call is deprecated...
    End If
Next oxFile
  • Related