When entries are made in a document, Word creates a Story Range to identify what part of the document is being used. These ranges can be used in macros to search for items , change text, or other actions.
This macro, for instance, changes the text in just the header of the first section:
Sub HeaderFooterObject() Dim MyText As String MyHeaderText = "This would be your text" With ActiveDocument.Sections(1) .Headers(wdHeaderFooterPrimary).Range.Text = MyHeaderText End With End Sub
When you use Edit>Replace in Word, it does a fine job of locating all occurrences of the target in the body of the document or in the header or footer.
Something fails, however, when you record the action and try to run it as a macro. To make it work, you must loop through the built in ranges of a Word document.
The exercise is interesting if only for the exposure to the built in ranges such as:
Find and replace with VBA
Also: Microsoft KB
VBA macro examples to insert text into a document
See all Topics word