VBA - saving a file to a directory

T

Tedsec

Okay, this one seems really silly, but I can't figure it out nor find
anything via google.

All i want to do is create a folder (in this example we'll call it
"Final Evals" and save a bunch of files there. This is the code I'm
using so far:


1 Sub DirTester()
2 Dim newDir As String
3
4 MsgBox CurDir
5
6 newDir = CurDir & ":Final Evals"
7 On Error Resume Next
8 MkDir newDir 'if the directory already exists, skip this line
9
10 ChDir newDir
11 MsgBox CurDir
12 ActiveDocument.SaveAs ("Hello")
13
14 End Sub



This is what I don't understand. When I run line 4 of the code, a
diretory is displayed. When I step through the code and get to line
11, the new directory is displayed (as I planned). Hence I would
assume it is now the default directory for the Open and Save comands.
But for some reason, the SaveAs command does not save to the new
directory. The new directory is created, but the file is saved under
the original directory displayed in line 4.

Does anyone know why VBA will create the new directory, set it as the
current directory, but then save back to the old one? does anyone know
how I can do this right?

Thanks in advance.
 
J

JE McGimpsey

Tedsec said:
Does anyone know why VBA will create the new directory, set it as the
current directory, but then save back to the old one? does anyone know
how I can do this right?

It's a bug...

The best practice, and a good workaround, is to fully qualify your path
and filename. Here's one way:

Public Sub DirTester2()
Dim sPS As String
Dim sNewDir As String
sPS = Application.PathSeparator
sNewDir = CurDir & sPS & "Final Evals"
If Len(Dir(sNewDir, vbDirectory)) = 0 Then MkDir sNewDir
ActiveDocument.SaveAs sNewDir & sPS & "Hello"
End Sub
 

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