Link to home
Start Free TrialLog in
Avatar of Andreas Hermle
Andreas HermleFlag for Germany

asked on

Kill files from excel (VBA)

Dear Experts:

Below code deletes all png files located in the folder "C:\Test\"

Could somebody please rewrite the code that the following requirements are met:

- nested subfolders under C:\Test\ should also be worked on
- all png-files should be deleted with the exception of file names with the following make-up: ##-###-##-##.png (e.g. 90-434-22-43.png or 55-234-55-07.png)
- will the below and revised code run on 64 bit windows Systems as well?

Help is much appreciated. Thank you very much in advance.

Regards, Andreas

Sub DeletePNGs()
Dim fs As FileSystemObject
Dim f As Object
Dim strFileName As String
Const strPath As String = "C:\Test\" 'The folder with the files
Set fs = CreateObject("Scripting.FileSystemObject")
strFileName = Dir$(strPath & "*.png")

While Len(strFileName) <> 0
    Set f = fs.GetFile(strPath & strFileName)
    Kill strPath & strFileName
    strFileName = Dir$()
Wend

Set f = Nothing
Set fs = Nothing
End Sub

Open in new window

Avatar of aikimark
aikimark
Flag of United States of America image

This should come close
Sub DeletePNGs()
    Dim fs As Object
    Dim f As Object
    Const strPath As String = "C:\test\" 'The folder with the files
    Set fs = CreateObject("Scripting.FileSystemObject")
    strFileName = Dir$(strPath & "*.png")
    For Each f In fs.GetFolder(strPath).Files
        If LCase(f.Name) Like "*.png" And Not (LCase(f.Name) Like "##-###-##-##.png") Then
            fs.Deletefile strPath & f.Name
        End If
    Next

    Set f = Nothing
    Set fs = Nothing

End Sub

Open in new window

Avatar of Bill Prew
Bill Prew

@aikimark

I think the OP also wanted to recursively drill into all subfolders.

~bp
@bp

Right you are.  Missed that requirement.  It's getting late and my eyes are starting to fuzz.  If the question is still open in the morning, I'll post an updated version of the code that will traverse the folders.
Avatar of Andreas Hermle

ASKER

Dear both,

thank you very much for your swift support.

Yes, as a matter of fact, I would like to have subfolders also worked on.

In the meantime, I will try your version on one folder.

Thank you

Regards, Andreas
ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Great job. Thank you very much for your great support.

The code first threw an error message: Permission denied. But I changed permission properties on the folder in question and everything went according to plan.

Again, thank you very  much for your great and professional help.

When I get back to my workplace next week, I will test this macro on my 64 bit Windows System. Hopefully, it will work there, too.

regards, Andreas