Creating a directory from within Word VBA

J

Jo Gjessing

Hi all,

I'm creating a little VBA script within Ms Word, wanting the script to
change directory before writing a file, using the ChangeFileOpenDirectory
method. It works fine. But what if the directory does not exist? Then I want
the script to create it. Can you please tell me how I make it do so?

Thank you very much in advance.

Jo
 
D

Doug Robbins - Word MVP

If you use the ChDir statement to try and change to a folder that does not
exist, it will return error number 76.

Hence, if you use the following code, it will create the folder:

On Error GoTo errHandler
ChDir "C:\this folder does not exist"

errHandler:
MsgBox Err.Number
If Err.Number = 76 Then
MkDir "c:\this folder does not exist"
End If


--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
F

fumei via OfficeKB.com

While not disputing that you CAN do this:

"wanting the script to change directory before writing a file,"

I have to ask why? In actual fact, ChangeFileOpenDirectory does just that,
change the file OPEN directory. Yes, you can then save a file to that folder.
..but in a sense, who cares? You can save a file to anywhere you want,
anyway.

Here is an alternative example with explicit path and filename, and error
handling if the folder does not exist. You know it has to be the folder path,
as the filename is valid. It will accept anything really.

myNew.docagshlashlasuwj is a valid filename.

Dim myFile As String
Dim myPath As String
On Error GoTo yadda
myPath = "c:\do-dah\"
myFile = "myNew.doc"
ActiveDocument.SaveAs FileName:=myPath & myFile
yadda:
If Err.Number = 5152 Then ' there is no c:\do-dah
MkDir myPath ' so make c:\do-dah
ActiveDocument.SaveAs FileName:=myPath & myFile
End If
 

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