VBA Working With Files and Directories Without Using FileSystemObject Creating and Deleting File Folders


Example


NOTE: For brevity, the examples below use the FolderExists function from the Determining If Folders and Files Exist example in this topic.


The MkDir statement can be used to create a new folder. It accepts paths containing drive letters (C:\Foo), UNC names (\\Server\Foo), relative paths (..\Foo), or the current working directory (Foo).

If the drive or UNC name is omitted (i.e. \Foo), the folder is created on the current drive. This may or may not be the same drive as the current working directory.

Public Sub MakeNewDirectory(ByVal pathName As String)
    'MkDir will fail if the directory already exists.
    If FolderExists(pathName) Then Exit Sub
    'This may still fail due to permissions, etc.
    MkDir pathName
End Sub

The RmDir statement can be used to delete existing folders. It accepts paths in the same forms as MkDir and uses the same relationship to the current working directory and drive. Note that the statement is similar to the Windows rd shell command, so will throw a run-time error 75: "Path/File access error" if the target directory is not empty.

Public Sub DeleteDirectory(ByVal pathName As String)
    If Right$(pathName, 1) <> "\" Then
        pathName = pathName & "\"
    End If
    'Rmdir will fail if the directory doesn't exist.
    If Not FolderExists(pathName) Then Exit Sub
    'Rmdir will fail if the directory contains files.
    If Dir$(pathName & "*") <> vbNullString Then Exit Sub
    
    'Rmdir will fail if the directory contains directories.
    Dim subDir As String
    subDir = Dir$(pathName & "*", vbDirectory)
    Do
        If subDir <> "." And subDir <> ".." Then Exit Sub
        subDir = Dir$(, vbDirectory)
    Loop While subDir <> vbNullString
    
    'This may still fail due to permissions, etc.
    RmDir pathName
End Sub