0

If I have a folder within a folder (subfolder). The subfolders name contains the word "Copy". How would I code in Excel to delete all subfolders containing this word?

I have managed this far, but it deletes all the subfolders.

Private Sub CommandButton1_Click()
    Dim FSO As Object
    Dim oPath As String

    Set FSO = CreateObject("scripting.filesystemobject")
    oPath = Blad1.Cells(2, 4).Value

    If Right(oPath, 1) = "\" Then
        oPath = Left(oPath, Len(oPath) - 1)
    End If

    If FSO.FolderExists(oPath) = False Then
        MsgBox oPath & " doesn't exist"
        Exit Sub
    End If

    On Error Resume Next
        'Delete files
        'FSO.deletefile oPath & "\*.*", True
        'Delete subfolders
        FSO.deletefolder oPath & "\*.*", True
    On Error GoTo 
End Sub
Community
  • 1
  • 1
Larome
  • 1
  • 1
    Try `FSO.DeleteFolder oPath & "\*Copy*", True`? Though you may need to do in a loop and delete each folder which name contains "copy" – David Zemens May 09 '17 at 14:11
  • Read here how to loop through Folders and Sub-Folders: http://stackoverflow.com/questions/22645347/loop-through-all-subfolders-using-vba – Shai Rado May 09 '17 at 14:14
  • Works super, Thanks alot David! no loop needed :) – Larome May 09 '17 at 14:14

0 Answers0