From: Nobody on
"Nobody" <nobody(a)nobody.com> wrote in message
news:OjWy0rGeKHA.5156(a)TK2MSFTNGP04.phx.gbl...
> "Karl E. Peterson" <karl(a)exmvps.org> wrote in message
> news:u643rMGeKHA.2164(a)TK2MSFTNGP02.phx.gbl...
>> Okay, gonna toss this one out to see who can shoot it down quickest...
>>
>> Public Function MkDirs(ByVal Folder As String) As Boolean
>> Dim f() As String
>> Dim attr As Long
>> Dim i As Long
>>
>> ' Split incoming folder into subfolders.
>> f = Split(Folder, "\")
>> For i = 1 To UBound(f)
>> f(i) = f(i - 1) & "\" & f(i)
>> Next i
>>
>> On Error Resume Next
>> For i = 0 To UBound(f)
>> ' Check if this level already exists.
>> attr = GetAttr(f(i))
>> If Err.Number Then
>> ' Folder likely doesn't exist,
>> ' clear error and create.
>> Err.Clear
>> MkDir f(i)
>> If Err.Number Then Exit For
>> End If
>> Next i
>>
>> ' Return success?
>> MkDirs = CBool(GetAttr(Folder) And vbDirectory)
>> End Function
>>
>> I've sure seen a lot of these over the years, but I guess never saw one I
>> liked enough to bother hanging onto. Anyone see a scenario this one
>> wouldn't handle?
>
> I prefer to use a for loop instead of Split. Example air code:
>
> Public Function MkDirs(ByVal Folder As String) As Boolean
> Dim attr As Long
> Dim i As Long
> Dim iStart As Long
>
> iStart =1 ' Start from the first character
> If Left(Folder, 2) = "\\" Then
> ' The folder is a share, skip to the third character
> iStart = 3
> End If
>
> On Error Resume Next
>
> For i = iStart To Len(Folder)
> If Mid(Folder, i, 1) = "\" Then
> attr = (GetAttr(Left(Folder, i)) And vbDirectory)
> If Err.Number <> 0 Then
> ' Folder likely doesn't exist,
> ' clear error and create.
> Err.Clear
> MkDir Left(Folder, i)
> If Err.Number Then Exit For
> End If
> End If
> Next
>
> ' Return success?
> MkDirs = CBool(GetAttr(Folder) And vbDirectory)
> End Function


My version of the code doesn't check or create the last folder if the last
character in the path isn't "\", so change this line:

If Mid(Folder, i, 1) = "\" Then

To:

If Mid(Folder, i, 1) = "\" Or i = Len(Folder) Then