INCLUDETEXT - replace bookmark name

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need to create a find/replace function that will allow me to replace the
bookmark name in the "INCLUDE TEXT" field. I've searched this site and found
an example that I'm testing with. As I debug this code, I see that "afield"
has the data that I need to change, all I really want to do is search for
AUGUST in the field and replace with SEPTEMBER, since I can't seem to get
that to work for me, I decided to search on the complete fieldcode, although
I'm getting a compiler error on my "afield.code like" statement.
Can anyone see what I'm doing wrong with this??

Dim afield As field
With ActiveDocument
For Each afield In .Fields
If afield.code = "INCLUDETEXT "\\\\NETWORK
SERVER\\dirNAME\\DIRECTORY2\\msword.doc " AUGUST" Then
afield.Select
Selection.Range.Text = "INCLUDETEXT "\\\\NETWORK
SERVER\\dirNAME\\DIRECTORY2\\msword.doc" SEPTEMBER"
End If
Next afield
End With
 
That's really the hard way. If you're using Word 2000 or later, the Replace
function makes it much easier to manipulate strings in macros. If the string
contains one substring, the function changes that part to a second
substring; otherwise nothing happens.

Try this code instead:

Dim afield As Field
With ActiveDocument
For Each afield In .Fields
If InStr(afield.Code.Text, "INCLUDETEXT ") > 0 Then
afield.Code.Text = Replace(afield.Code.Text, _
"AUGUST", "SEPTEMBER")
End If
Next afield
.Fields.Update
End With

A couple more things that you should notice:

- It's a good idea to avoid the Selection object when you can, and this is a
case where you can avoid it. The macro can change all the field codes
without moving the cursor around.

- The Instr function returns the position of the second argument within the
first argument, or 0 if the second argument doesn't occur. That's a quick
way of finding out whether "INCLUDETEXT" occurs in the field code. You don't
need to do a comparison on the whole code string, because nothing will
happen to the field if it doesn't contain "AUGUST".

- Technically, afield.Code is a Range object, not a string. That's why I
used afield.Code.Text. It makes a difference when you're replacing one
string with another -- you get an error if you leave it out.

- The macro should finish by updating the fields, because otherwise it will
appear that nothing happened.

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