SaveAs File Permission Error

P

Poseur

This is not a question but an answer to one that has not been
asked. Recently.
I wanted to save a new document as "firstline text".doc
Public Sub SaveTest()
Dim fn As String
Selection.HomeKey Unit:=wdStory
Selection.Expand (wdLine)
fn = Selection.Text
fn = "d:\documents and settings\...\" & fn
ActiveDocument.SaveAs FileName:=fn, _
FileFormat:wdFormatDocument
End Sub
Kept getting file permission error.

The problem apparently is that the selected text included the
carriage return at the end.
This works:
....
fn = Selection.Text
fn = "d:\documents and settings\dan\my documents\" & Left(fn,
Len(fn) - 1)
ActiveDocument.SaveAs FileName:=fn, FileFormat:
=wdFormatDocument

So, next time someone does a google search on this, maybe this
will be helpful.
 
J

Jay Freedman

I'm glad you were able to find the cause of the problem. The solution
you came up with, though, isn't very robust. Think about what happens
if the text you selected before you run the macro didn't include a
paragraph mark at the end, but was just the part you wanted as the
filename. Now your code would remove the last character, giving you a
file that would save, but not with the name you expected.

A better solution for Word 2000 and later versions is

....
fn = Selection.Text
fn = "d:\documents and settings\dan\my documents\" & _
Replace(fn, vbCr, "")
ActiveDocument.SaveAs FileName:=fn, _
FileFormat:=wdFormatDocument

If there is a paragraph mark (vbCr) anywhere in the selected text, the
Replace function will remove it (replace it with nothing). If there
isn't one, the Replace function won't do anything.

If you're dealing with Word 97, it doesn't have the Replace function,
so you need to use an If...Then construction to see whether there is a
vbCr in Selection.Text.
 
P

Poseur

I'm glad you were able to find the cause of the problem.
The solution you came up with, though, isn't very robust.
Think about what happens if the text you selected before
A better solution for Word 2000 and later versions is
...
fn = Selection.Text
fn = "d:\documents and settings\dan\my documents\" & _
Replace(fn, vbCr, "")
ActiveDocument.SaveAs FileName:=fn, _
FileFormat:=wdFormatDocument

Yup. Thanks.
 

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