Friday, February 24, 2012

Use VBA to Delete all files in folder

Below there are two examples that delete every file in a folder Test in your documents folder.
The first will delete the files from your system and the second one will move the files to the Trash.
Note: see the wilcard * in the first macro, you can change that to for example *.pdf or *.docx

Sub DeleteFilesInFolder()
    Dim FolderWithFiles As String
    Dim scriptToRun As String

    FolderWithFiles = MacScript("return (path to documents folder) as string") & "Test:"

    scriptToRun = scriptToRun & "tell application " & Chr(34) & _
                  "Finder" & Chr(34) & Chr(13)
    scriptToRun = scriptToRun & _
                  "do shell script ""rm "" & quoted form of posix path of " & _
                  Chr(34) & FolderWithFiles & """ & " & Chr(34) & "*" & Chr(34) & Chr(13)
    scriptToRun = scriptToRun & "end tell"

    On Error Resume Next
    MacScript (scriptToRun)
    On Error GoTo 0
End Sub


Sub MoveFilesInFolderToTrash()
    Dim FolderWithFiles As String

    FolderWithFiles = MacScript("return (path to documents folder) as string") & "Test:"
   
    scriptToRun = scriptToRun & "tell application " & Chr(34) & _
                  "Finder" & Chr(34) & Chr(13)
    scriptToRun = scriptToRun & "delete (every item of folder " & _
                  Chr(34) & FolderWithFiles & Chr(34) & ")" & Chr(13)
    scriptToRun = scriptToRun & "end tell" & Chr(13)

    On Error Resume Next
    MacScript (scriptToRun)
    On Error GoTo 0

End Sub

No comments:

Post a Comment