0
votes

There's a bunch of questions here asking how to get all headings, but apparently nobody tried to change a heading ...

I want to change some second level headings from Old Heading to New Heading, so I did this ...

Sub changeHeading()
    Dim p As Paragraph
    For Each p In ActiveDocument.Paragraphs
        If p.Style = "Heading 2" Then _
            If p.Range.Text = "Old Heading" & vbCr Then p.Range.Text = "New Heading" & vbCr
    Next p
End Sub

The headings get the new name, but they also get a different style - they get the style of the following paragraph - i.e. if the text after the heading had style table text the heading will have style table text afterwards (the font size will remain the one from the old heading), the numbering of the chapters is lost. If I set the style back p.Style = "Heading 2" this will make the first text after that heading (i.e. the next paragraph) having the Heading 2 style, though it's still the same paragraph p (with changed text, but same position in the document).

Situation before:

1.4 Old Heading
some text

after changing the heading and setting back the style

New Heading
1.4 some text    

Where some text has the style Heading 2 and New Heading has font size of the heading, but no numbering.

Second problem, it takes unbelievable long (some seconds for a small document with just few paragraphs).

So, how to change a heading? And how to do it in a way that won't take minutes on a big document? Thanks for any help.

EDIT:

I found that changing the text with

Call p.Range.Find.Execute(FindText:="Old Heading", ReplaceWith:="New Heading")

will keep the style, so this will solve my original problem of changing the text, but I'd still like to know why setting the paragraphs text makes it loosing its style.

1

1 Answers

1
votes

The reason the style is changing is because you're overwriting the paragraph mark (vbCr). The paragraph-level formatting is associated directly with the paragraph character. When you delete it, then insert another at the start of the next paragraph, the new paragraph will adopt the formatting of the paragraph in which it originated.

And incidentally, using Range.Find with Replace would probably be much more efficient than looping the paragraphs collection. Word's Find functionality can also search for formatting. So you can use a single Find action to locate both the Heading 2 style AND the specific text (without the paragraph mark). And then use Replace to write the new text.

Test in the Word UI, then record a macro to get the basic syntax.