Reputation: 139
I'm trying to delete all files in a directory apart from 4 files. I know how to delete all except specific files using the code below, but I'm sure it could be improved. Is there a shortened command that I've not found?
Sub Kill_Files()
Dim fname As String
fname = Dir$(ThisWorkbook.Path & "\*.*")
Do While Len(fname) > 0
If Left(fname, 10) <> "AAAAAAAAAA" Then
If Left(fname, 10) <> "BBBBBBBBBB" Then
If Left(fname, 10) <> "CCCCCCCCCC" Then
If Left(fname, 10) <> "DDDDDDDDDD" Then
Kill fname
End If
End If
End If
End If
fname = Dir$
Loop
End Sub
Upvotes: 1
Views: 2812
Reputation: 3284
If you are asking how to consolidate your If
statements, you could rewrite this Sub
as:
Sub Kill_Files()
Dim fname As String
fname = Dir$(ThisWorkbook.Path & "\*.*")
Do While Len(fname) > 0
If Left(fname, 10) <> "AAAAAAAAAA" And Left(fname, 10) <> "BBBBBBBBBB" And Left(fname, 10) <> "CCCCCCCCCC" And Left(fname, 10) <> "DDDDDDDDDD" Then
Kill fname
End If
fname = Dir$
Loop
End Sub
Upvotes: 1
Reputation: 1715
You could remove the nested IF
s by:-
Sub Kill_Files()
Dim fname As String
fname = Dir$(ThisWorkbook.Path & "\*.*")
Do While Len(fname) > 0
If Not (Left(fname, 10) = "AAAAAAAAAA" _
Or Left(fname, 10) = "BBBBBBBBBB" _
Or Left(fname, 10) = "CCCCCCCCCC" _
Or Left(fname, 10) = "DDDDDDDDDD") Then
MsgBox fname '<-- change this back to a Kill to see the code in action
End If
fname = Dir$
Loop
End Sub
Upvotes: 1