PDA

View Full Version : Solved: If Dir/MkDir causes Error if folder is empty



kv2e
11-22-2010, 05:30 PM
My VBA script in a word template is checking to see if a folder exists, then if it doesn't, creates the folder and (not shown) saves the word doc.

It works perfectly - unless the folder exists but is empty, in which case it returns an error (apparently, the If Dir statement thinks the folder doesn't exist, if empty). I tried removing the trailing \ in the FolderPath with the same result.

Here is my code:

Dim Uname As String
Dim FolderPath As String

Uname = Environ("USERNAME")
FolderPath = "C:\Documents and Settings\" & Uname _
& "\My Documents\Recipes\"

' Check if Recipe folder exists, if not create it.

If Dir(FolderPath) = "" Then
MkDir FolderPath
End If

Any suggestions??

Thanks!
Bill (kv2e)

macropod
11-22-2010, 08:00 PM
Hi Bill,

You could probably get away with adding 'On Error Resume Next' before the 'If' test. Alternatively, for a more robust solution:
Dim fso, Uname As String, FolderPath As String
Set fso = CreateObject("Scripting.FileSystemObject")
Uname = Environ("USERNAME")
FolderPath = "C:\Documents and Settings\" & Uname & _
"\My Documents\Recipes\"
' Check if Recipe folder exists, if not create it.
If Not fso.FolderExists(FolderPath) Then MkDir FolderPath
Set fso = Nothing
Note: You'll need to make some more changes to your code for use with Windows Vista?/7 and later, as 'C:\Documents and Settings\' has been replaced with 'C:\Users\' and '\My Documents\' has been replaced with 'Documents\' (even though 'My Documents' shows in the Windows Explorer Title Bar).

kv2e
11-23-2010, 09:06 AM
macropod,

I incorporated the more robust solution you suggest, and of course it works perfectly.

I imagine I should also include an 'If Then' to set the unique path for the different OS versions as you point out.

Curious... why is it necessary to set fso = nothing at the end of the If Not statement?

Thanks again.

macropod
11-23-2010, 12:04 PM
Hi Bill,

It is good practice to destroy objects you've created when you're finished with them, so as to guarantee release of the memory they required.