Search code examples
vbafso

DeleteFolder method of FileSystemObject Does Not Give an Error (MSDN lied to me)


I have a couple folders on my desktop which I used temporarily for a macro. Now, I want to delete them. One is a .zip and one is a regular folder.

Set fso = CreateObject("scripting.filesystemobject")
fso.DeleteFolder unzipPath, True

The above code works without error. The non-.zip folder is deleted without issues. This, however, does not remove the file:

On Error GoTo 0
fso.DeleteFolder zipPath, True

Contrary to the MSDN documentation, this does not create an error, either. After far too much time, I realized I simply needed to use DeleteFile for the .zip, since apparently a .zip is technically a file, rather than a folder. Then both items are deleted successfully.

It works now, but I'm still a bit confused as to why using DeleteFolder did not produce an error, though. The aforementioned documentation specifies

An error occurs if no matching folders are found.

UPDATE: For the sake of testing, I created a standalone sub exclusively to test the DeleteFolder on a .zip. The .zip is unchanged; there is no error returned; the sub just ends.

Just a curious soul wandering the realms of VBA...


Solution

  • This behavior is not limited to .ZIP files (which is what Compressed Folders really are). What is interesting is that the DeleteFile method will not throw an error when attempting to delete an existing folder, and the DeleteFolder method does not error when attempting to delete an existing file. The only way I got the to error was by specifying a non-existent file/folder name.


    Yes, it appears MSDN is wrong. Try this:

    Sub IO_Error()
        Dim objFSO As FileSystemObject
        Dim strTempDir As String
    
        Set objFSO = New FileSystemObject
        strTempDir = Environ("Temp")
        Debug.Print strTempDir & "\IO Test"
        objFSO.CreateFolder strTempDir & "\IO Test"
        objFSO.CreateTextFile strTempDir & "\IO Test\IO Test.txt", True
    
        objFSO.DeleteFolder strTempDir & "\IO Test\IO Test.txt", True   'No errors
        objFSO.DeleteFile strTempDir & "\IO Test", True                 'No errors
        objFSO.DeleteFile strTempDir & "\IO Test\", True                'File not found error
    
    End Sub