ERLANDSEN DATA CONSULTING Excel & VBA Tips   Informasjon på norsk / Information in Norwegian

These pages are no longer updated and are only available for archive purposes.

Click here to visit the pages with updated information.

Create new folders

The function below can determine if a folder exists, it can also create any missing folders ine the folder path:

Function FolderExists(strInputFolder As String, blnCreate As Boolean) As Boolean
' returns true or false if the folder exists, can create any missing folders
' example: If Not FolderExists("C:\FolderName\SubFolder", False) Then Exit Sub
' example: If Not FolderExists("C:\FolderName\NewFolder", True) Then Exit Sub
Dim strFolder As String, varrFolders As Variant, i As Long
    FolderExists = False
    ' validate input
    If InStr(1, strInputFolder, ":", vbBinaryCompare) <> 2 Then Exit Function
    If InStr(1, strInputFolder, "\", vbBinaryCompare) = 0 Then Exit Function
    If blnCreate Then ' try to create any missing folders
        ' split path into separate folders
        varrFolders = Split(strInputFolder, "\", -1, vbBinaryCompare)
        strFolder = varrFolders(LBound(varrFolders)) ' drive letter
        For i = LBound(varrFolders) + 1 To UBound(varrFolders)
            strFolder = strFolder & "\" & varrFolders(i) ' add folder to path
            If Not Len(Dir(strFolder, vbDirectory)) > 0 Then
                On Error Resume Next
                MkDir strFolder ' create new folder
                On Error GoTo 0
            End If
        Next i
        Erase varrFolders
        ' check and see if the folder exists
        FolderExists = Len(Dir(strFolder, vbDirectory)) > 0
    Else ' just check and see if the folder exists
        FolderExists = Len(Dir(strInputFolder, vbDirectory)) > 0
    End If
End Function


Document last updated 2005-04-26 10:49:54      Printerfriendly version

User comments:
Ole P. from Norway wrote (2005-04-27 00:40:11 CET):
Re: Create new folders-network folder handlers
You will have to remove the first line that validates the input and probably make som more minor changes to the code to make it work properly in a network environment.
Alexander Crokos from Jersey City, USA wrote (2005-04-26 18:02:06 CET):
Create new folders-network folder handlers
how would you handle network file folder name "\\Crokos-00\E_00\"


Erlandsen Data Consulting   
Excel & VBA Tips   Copyright ©1999-2018    Ole P. Erlandsen   All rights reserved
E-mail Contact Address