Friday, February 24, 2012

Use VBA Kill to delete files

If you use the Kill command on a Mac be aware that there is a file name(with extension) limit of 32 characters.
Be sure that you use shorter file names or use a MacScript.

This will blow on a Mac for example (file not found error)

Kill "Macintosh HD:Users:rondebruin:Documents:Part of SendMail(Attachment)Testers.xls 12-jul-11 15-22-04.xls"

You can use this Mac Script instead if you can't be sure that you are below the limit.

Sub DeleteFileOnMac()
Dim scriptToRun As String
Dim Filestr As String

Filestr = "Macintosh HD:Users:rondebruin:Documents:Part of SendMail(Attachment)Testers.xls 12-jul-11 15-22-04.xls"

scriptToRun = scriptToRun & "tell application " & Chr(34) & "Finder" & Chr(34) & Chr(13)
scriptToRun = scriptToRun & "delete file " & Chr(34) & Filestr & Chr(34) & Chr(13)
scriptToRun = scriptToRun & "end tell"

MacScript (scriptToRun)

End Sub

Note: that Kill remove the file from your system and the applescript example above move it to the Trash.

But you can also use this instead of Kill if you really want to delete the file :

Sub DeleteFile()
    Dim FileName As String
    Dim scriptToRun As String

    'Delete file ron.xlsm on your desktop
    FileName = MacScript("return (path to desktop folder) as string") & "ron.xlsm"

    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) & FileName & Chr(34) & Chr(13)
    scriptToRun = scriptToRun & "end tell"

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


Or you can use the function KillFileOnMac below to delete a file, you can call it in your macro like this :
KillFileOnMac "Macintosh HD:Users:Ron:Documents:YourFileName.xlsm"

Function KillFileOnMac(Filestr As String)
    Dim ScriptToKillFile As String
    ScriptToKillFile = ScriptToKillFile & "tell application " & Chr(34) & _
                  "Finder" & Chr(34) & Chr(13)
    ScriptToKillFile = ScriptToKillFile & _
                  "do shell script ""rm "" & quoted form of posix path of " & _
                  Chr(34) & Filestr & Chr(34) & Chr(13)
    ScriptToKillFile = ScriptToKillFile & "end tell"

    On Error Resume Next
    MacScript (ScriptToKillFile)
    On Error GoTo 0
End Function

No comments:

Post a Comment