How to search and replace in document header

T

Tomas Eklund

Using Word 2003

This is my first time using VBA and I am trying to learn by the help file,
which isn't very helpful.

I have created a .dot template with some text and a simple form with 12
text fields. The form appears when a new document based on the template is
created. The user inputs stuff into the text fields of the form and clicks
the OK button. The script then replaces placeholders in the text with the
values specified by the user.

Something like:

Private Sub ButtonOK_Click()
With ActiveDocument.Content.Find
.ClearFormatting
.Execute FindText:="[Placeholder1]", _
ReplaceWith:=TextBox1.Text, _
MatchCase:=False, _
Wrap:=wdFindContinue, _
Replace:=wdReplaceAll
.Execute FindText:="[Placeholder2]", _
ReplaceWith:=TextBox2.Text, _
MatchCase:=False, _
Wrap:=wdFindContinue, _
Replace:=wdReplaceAll
' And so on...
End With
MyForm.Hide
End Sub

Everything seems to work as I expect it except for one thing: The
placeholders that are within the page header are never replaced. I really
don't understand why. When using Word's built-in Search-and-Replace the
headers are searched through, but not from code. What am I missing here?
 
H

Helmut Weber

Hi Tomas,
Everything seems to work as I expect it except for one thing: The
placeholders that are within the page header are never replaced. I really
don't understand why. When using Word's built-in Search-and-Replace the
headers are searched through, but not from code. What am I missing here?

Not much, it is just that Word's document design
and it's interaction with VBA is less than perfect.

see:
http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm

better use bookmarks instead of placeholders:
http://word.mvps.org/faqs/macrosvba/WorkWithBookmarks.htm
http://word.mvps.org/faqs/macrosvba/InsertingTextAtBookmark.htm

--
Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
 

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