Replacement Macro for styles




I am writing a macro to replace several styles in a document with new
styles. I used the Macro recorder with the Find-Replace feature in Word but
the macro is not working. I get the Run time error. I am still learning how
to manipulate recorded macros using VBA. I have included a short one below -
it is replacing Heading 1 style with Heading 2: Topic style. Can someone take
a look at it and let me know if anything jumps out at you as incorrect.

Sub TestUpdate()
' TestUpdate Macro
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Replacement.Style = ActiveDocument.Styles("H1:Lesson")
Selection.Find.Replacement.ParagraphFormat.Borders.Shadow = False
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub



Jay Freedman

Whenever you ask questions about errors in macros, it's vitally
important to quote exactly the text of the error message. We aren't
mind readers (well, not usually). In this case, though, I can guess
that the error you saw said "Run-time error '5941': The requested
member of the collection does not exist". When that appears, if you
click the Debug button, you'll probably see this line highlighted in

Selection.Find.Replacement.Style = ActiveDocument.Styles("H1:Lesson")

It's telling you that there is no style in the current document with
the name "H1:Lesson".

When I copied your code into the VBA editor and ran it on a document
where I created a style with that name, the macro ran perfectly --
there's nothing wrong with the code except that it doesn't gracefully
handle the absence of the replacement style.

The macro could be cleaned up a bit -- see for
hints -- but the cause of the error lies outside the macro itself.

BTW, further questions about macros should be posted in the newsgroup

Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.




Jay - thank you! You have really been a life-saver over the last week.

I will go to that board in future.


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