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
Hello David
For this to do is in VBA many ways.
This can be just one alternative is.
' 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
Alan, still waiting your suggestion, anyway thanks in advance
Thanks Alan, I try it, now the loop become perfect.