Forum

Delete specific Fil...
 
Notifications
Clear all

Delete specific Files in a folder

4 Posts
2 Users
0 Reactions
109 Views
(@david_ng)
Posts: 310
Reputable Member
Topic starter
 

I have more than two hundred files generated from System then store in the following path and Folder, but some of these files I don't need to send to my clients, so I want to delete these files using below vb script, it works ,though, it seems too clumsy.

Please help to enhance or modify these codes to make it professional.    

ChDir "C:BookDataAR"
myName = "C:BookDataARSheet2.xlsx"
myName1 = "C:BookDataARDCH.xlsx"
myName2 = "C:BookDataARKBR.xlsx"
myName3 = "C:BookDataARLOEWE.xlsx"
myName4 = "C:BookDataARMDHKG.xlsx"
If Len(Dir(myName)) > 0 Then
Kill myName
If Len(Dir(myName1)) > 0 Then
Kill myName1
If Len(Dir(myName2)) > 0 Then
Kill myName2
If Len(Dir(myName3)) > 0 Then
Kill myName3
If Len(Dir(myName4)) > 0 Then
Kill myName4
End If
End If
End If
End If
End If
End Sub

 
Posted : 20/01/2021 11:03 pm
(@doc-aelstein)
Posts: 21
Eminent Member
 

Hello David

For this to do is in VBA many ways.

This can be just one alternative is.

https://pastebin.com/RndgWj8e

'   https://www.myonlinetraininghub.com/excel-forum/vba-macros/delete-specific-files-in-a-folder  

Sub Trashit()

Rem 1 Workbooks info

Const Ext As String = "xlsx"

Const FldrPth As String = "C:BookDataAR"

'Dim FldrPth As String: Let FldrPth = ThisWorkbook.path ' can be used if macro is in file in same filder as files to be killded

Dim arrNms() As Variant: Let arrNms() = Array("Sheet2", "DCH") ' <---  Add all your names here, - But note alsoThis can it be also be got from other lists programatically maybe

Rem 2 Do it

Dim StearIsIt As Variant ' For each of it is in Variant type

    For Each StearIsIt In arrNms()

        If Len(Dir(FldrPth & Application.PathSeparator & StearIsIt & "." & Ext & "", vbNormal)) > 0 Then Kill FldrPth & Application.PathSeparator & StearIsIt & "." & Ext

    Next StearIsIt

End Sub

 

For example:

If like your list of  file names was in a column, maybe column A, in a worksheet with tab Name “MySheet”,  then it could be like

 Let arrNms() = Worksheets("MySheet").Range("A1:A250").Value2 ' <---  change 250 to your last row number

 

Alan

 
Posted : 21/01/2021 8:16 am
(@david_ng)
Posts: 310
Reputable Member
Topic starter
 

Alan, still waiting your suggestion, anyway thanks in advance

 
Posted : 21/01/2021 10:23 am
(@david_ng)
Posts: 310
Reputable Member
Topic starter
 

Thanks Alan, I try it, now the loop become perfect.

 
Posted : 21/01/2021 8:05 pm
Share: