I am trying to create a macro that will find every occurance of a word and
index it. Is there a simple way of doing this (e.g., something equivalent
to "wdReplaceAll" in the find) or do I have to set up a loop to find next
occurance and then mark it? If the latter, how do I test to see if the
find was successful.
Thanks for any help.
Jerry
Hi Jerry,
You can do it either way. In a large document where the selected word
occurs many times, the wdReplaceAll will be faster; the loop will be a
little easier to program.
If you want to use wdReplaceAll, then you'll need to get the word and
the corresponding index entry field together on the clipboard, and use
the ^c code to insert the clipboard contents in the document wherever
the word occurs. This macro does it by building the term and field at
the end of the document and then cutting it to the clipboard.
Sub IndexAllOccurrences_1()
Dim strTarget As String
Dim oRg As Range
' get index term
strTarget = InputBox$("Enter term to index:")
If Len(strTarget) = 0 Then Exit Sub
' make a copy of the term and its index field
' at the end of the document, then cut it
' to the clipboard
Set oRg = ActiveDocument.Range
With oRg
.Collapse wdCollapseEnd
ActiveDocument.Fields.Add Range:=oRg, _
Type:=wdFieldIndexEntry, _
Text:=strTarget
.InsertBefore strTarget
.End = ActiveDocument.Range.End - 1
.Cut
End With
' replace each occurrence of the term
' with the clipboard contents
Set oRg = ActiveDocument.Range
With oRg.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = strTarget
.Replacement.Text = "^c"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchWildcards = False
.Execute Replace:=wdReplaceAll
End With
End Sub
Alternatively, you can run a loop that finds one occurrence of the
word at a time, and inserts the field each time. The key to this is
the statement 'Do While .Execute'. Each time this line runs, the
..Execute method tries to find the word; if it's successful, the range
is redefined to cover only that word and the method returns the value
True, which causes the body of the loop to run again.
Sub IndexAllOccurrences_2()
Dim strTarget As String
Dim oRg As Range
' get index term
strTarget = InputBox$("Enter term to index:")
If Len(strTarget) = 0 Then Exit Sub
Set oRg = ActiveDocument.Range
With oRg.Find
.ClearFormatting
.Text = strTarget
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = False
' when .Execute finds an occurrence,
' it returns the value True and
' redefines the range oRg to cover
' the found text
Do While .Execute
oRg.Collapse wdCollapseEnd
ActiveDocument.Fields.Add Range:=oRg, _
Type:=wdFieldIndexEntry, _
Text:=strTarget
oRg.Collapse wdCollapseEnd
Loop
End With
End Sub
--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.