Using VBA to create folder

J

Joe

I have code that creates a bunch of csv files from the
data in a workbook. Here are a couple of excerpts from
my code:

fldr = InputBox("Enter Directory Name", "CSV FILE
LOCATION")
..
..
..
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(fldr) Then
fs.CreateFolder fldr
End If

If the user enters c:\joe\ and c:\joe\ doesn't exist,
then the code will create a folder called c:\joe\.

If the user enters c:\joe\bob\ and c:\joe\bob\ doesn't
exist, then the code will create a folder called
c:\joe\bob\ BUT ONLY if c:\joe\ exists. If c:\joe\
doesn't exist, I get a run-time error. Is there a
solution to the problem? I don't want my macro to
terminate if the folder doesn't exist.
 
J

Jim Rech

Try this code:

Declare Function MakePath Lib "imagehlp.dll" Alias _
"MakeSureDirectoryPathExists" (ByVal lpPath As String) As Long

Sub Test()
MakeDir "c:\aaa\bbb"
End Sub

Sub MakeDir(DirPath As String)
If Right(DirPath, 1) <> "\" Then DirPath = DirPath & "\"
MakePath DirPath
End Sub


--
Jim Rech
Excel MVP

|I have code that creates a bunch of csv files from the
| data in a workbook. Here are a couple of excerpts from
| my code:
|
| fldr = InputBox("Enter Directory Name", "CSV FILE
| LOCATION")
| .
| .
| .
| Set fs = CreateObject("Scripting.FileSystemObject")
| If Not fs.FolderExists(fldr) Then
| fs.CreateFolder fldr
| End If
|
| If the user enters c:\joe\ and c:\joe\ doesn't exist,
| then the code will create a folder called c:\joe\.
|
| If the user enters c:\joe\bob\ and c:\joe\bob\ doesn't
| exist, then the code will create a folder called
| c:\joe\bob\ BUT ONLY if c:\joe\ exists. If c:\joe\
| doesn't exist, I get a run-time error. Is there a
| solution to the problem? I don't want my macro to
| terminate if the folder doesn't exist.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top