Loop through files and delete with a condiiton

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

Loop through files and delete with a condiiton

Post by YasserKhalil »

Hello everyone
As a part of a code that generates png files with specific names I have this part

Code: Select all

    sFileName = Dir(sFolder)
    While sFileName <> ""
        If Val(Split(sFileName, "-")(1)) Mod 3 <> 2 Then
            DoEvents
            Kill sFolder & sFileName
        End If
        sFileName = Dir
    Wend
I tried to debug.print inside the condition and the files that is supposed to be deleted are listed successfully. But when trying the code, nothing of the files are deleted at all
What is weird is that when using F8 to run the code line by line, the files deleted. I tried DoEvents part but the problem is still there.
Any ideas?

User avatar
HansV
Administrator
Posts: 78474
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Loop through files and delete with a condiiton

Post by HansV »

That's hard to say. I created a folder with some files and ran your code (without DoEvents). The files matching the condition were deleted as intended.
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

Re: Loop through files and delete with a condiiton

Post by YasserKhalil »

Here's the code to test

Code: Select all

Sub zzzz()
    Const sEXEPATH As String = "C:\Users\Future\Desktop\poppler-20.11.0\bin\pdfimages.exe"
    Const sPDFName As String = "Final.pdf"
    Const sDestFolder As String = "Output"
    Dim sFileName, sFolder As String, sPDFFile As String
    sFolder = ThisWorkbook.Path & "\" & sDestFolder & "\"
    If Len(Dir(sFolder, vbDirectory)) = 0 Then MkDir sFolder
    sPDFFile = ThisWorkbook.Path & "\" & sPDFName
    
Shell """" & sEXEPATH & """ -all """ & sPDFFile & """ """ & sFolder & "Image"""
    
    sFileName = Dir(sFolder)
    While sFileName <> ""
        If Val(Split(sFileName, "-")(1)) Mod 3 <> 2 Then
            Debug.Print sFileName
            'DoEvents
            'Kill sFolder & sFileName
        End If
        sFileName = Dir
    Wend

Debug.Print "Done..."
End Sub
Here's the link of poppler windows
https://github.com/oschwartz10612/poppl ... g/v20.11.0

And here's sample pdf file
https://we.tl/t-ElxrIhMbfI

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

Re: Loop through files and delete with a condiiton

Post by YasserKhalil »

I had an idea and worked well ..
The solution would be

Code: Select all

    Application.Wait Now + TimeValue("00:00:05")
    sFileName = Dir(sFolder)
So to deal with the files, I should put waiting for some time so as to let it work well.