Replacement Macro for styles


G

Guest

Hi,

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.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 2")
Selection.Find.Replacement.ClearFormatting
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
 
Ad

Advertisements

J

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
yellow:

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
http://www.word.mvps.org/FAQs/MacrosVBA/ModifyRecordedMacro.htm for
hints -- but the cause of the error lies outside the macro itself.

BTW, further questions about macros should be posted in the newsgroup
microsoft.public.word.vba.beginners
(http://www.microsoft.com/communitie...3e4-379a-4ba1-aade-bee89d80f3ec&lang=en&cr=us).

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

Advertisements

G

Guest

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

I will go to that board in future.

Sincerely,
Tara
 

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