Want to earn $25 for telling us how you feel about the current Microsoft Learn Q&A thread experience? Help our research team understand how to make Q&A great for you.
'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
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