Share via

Word visual basic code

Anonymous
2012-04-21T18:32:30+00:00

'Following is Word macro that does not run.  Please advise what the problem is.

'Thanks.Jim

Sub SaveDoc()

'this routine is supposed to use the first line of a word document as the name of the file to be stored in C:\junk

'it doesn't run for my Word 2003 document in Windows 7  I get run time error 5487

'note if SSS="test" in the code then it runs OK.  What is the problem.  The captured SSS looks OK.

Dim SSS As String

    Selection.HomeKey Unit:=wdStory

    Selection.EndKey Unit:=wdLine

    Selection.Extend

    Selection.Extend

    Selection.Extend

    SSS = Selection.text

    SSS = "test"

    SSS = "C:\junk" & SSS

    ActiveDocument.SaveAs FileName:=SSS

End Sub

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2012-04-21T20:31:29+00:00

If the first line of the document ends with a paragraph mark -- that is, if the first line is the same thing as the first paragraph -- then after the statement SSS = Selection.text the string contains the paragraph mark at its end. The paragraph mark isn't a valid character in a file name, so the SaveAs method fails.

You can avoid this error by adding this line in the place where you've temporarily inserted SSS = "test" :

   SSS = Replace(SSS, Chr(13), "")

This will replace the paragraph mark with nothing, and it won't do anything if there isn't a paragraph mark. You can also improve the readability of the macro by removing the three Selection.Extend statements and instead changing the EndKey statement to

    Selection.EndKey Unit:=wdLine, Extend:=True

If you know that the first line is the same thing as the first paragraph, you can shorten the code a bit -- and avoid moving the selection in the document -- by doing this:

Sub SaceDocBetter()

    Dim SSS As String

    SSS = ActiveDocument.Paragraphs(1).Range.Text

    SSS = Replace(SSS, Chr(13), "")

    SSS = "C:\temp" & SSS & ".doc"

    ActiveDocument.SaveAs FileName:=SSS

End Sub

Was this answer helpful?

4 people found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Anonymous
    2012-04-28T11:38:12+00:00

    Jay,

    Thank you for your help.  The code worked fine.   I am slowly learning my way.

    Jim

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments
  2. Anonymous
    2012-04-21T22:42:44+00:00

    That did the trick.  I really appreciate your rapid response and the time you spent on this frustrating problem I encountered.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments