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.