Replaces files

R

Richstein

I have the following code written to save files in a
certain location. However, if the file already exists, no
prompt appears asking if I want to replace. Is there a
way to do this? Thank you.

Sub Saveit()
Dim fileName As String

fileName = InputBox("Enter File Name")

ActiveDocument.SaveAs "F:\class\" & fileName



End Sub
 
J

Jezebel

Two approaches you can take. Either test whether the file exists:

if len(dir(fileName)) > 0 then
.. file exists
end if

Or, since you're prompting for the filename anyway, use the CommonDialog
control instead of the inputbox (which is a much better way to get a
filename anyway). Add a form, and put a CommonDialog control on it. You
don't need to display the form. IN your macro, use code like

With new MyForm.CommonDialog1
.InitDir = .... 'Folder to save in
.Flags = cdlOFNOverwritePrompt (+ cdlOFNNoChangeDir if users
MUST save in this folder)

etc ... Check Help for the full set of arguments

End with
 
R

Richstein

I tried the first suggestion, it still does not prompt me
if the file exists. What am I missing? Thanks for the
help!

Dim fileName As String
If Len(Dir(fileName)) > 0 Then

fileName = InputBox("Enter File Name")

ActiveDocument.SaveAs "F:\class\" & fileName

End If
 
J

Jay Freedman

I'm afraid you're missing the entire point of the exercise. Think in words
first, then in code:

- Ask the user for a name to use.
- Test whether a file already exists with that name.
- If it exists, ask whether to replace. Otherwise, just save the file with
that name.

The "ask for a name" part corresponds to the InputBox statement. This should
come first.

The "test whether a file exists" part corresponds to the If
Len(Dir(fileName)) > 0 statement. The "ask whether to replace" part
corresponds to a MsgBox statement that you should have in the Then part of
the If statement (which you don't do), while the "just save the file" part
corresponds to an Else part of the If statement (which is also missing from
your macro).
 

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