Question

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
Was it helpful?

Solution

You could remove the nested IFs 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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top