Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
DiscussionsAccessExcelInfoPathOutlookPowerPointPublisherWord
DirectoryUser Groups
Related Topics
Outlook ExpressInternet ExplorerWindowsMS Server ProductsMore Topics ...

MS Office Forum / Word / Programming / March 2008

Tip: Looking for answers? Try searching our database.

Creating a directory from within Word VBA

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Jo Gjessing - 31 Mar 2008 12:51 GMT
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
Doug Robbins - Word MVP - 31 Mar 2008 13:37 GMT
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

Signature

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

> Hi all,
>
[quoted text clipped - 7 lines]
>
> Jo
fumei - 31 Mar 2008 20:14 GMT
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

>Hi all,
>
[quoted text clipped - 6 lines]
>
>Jo
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2010 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.