PDA

View Full Version : Solved: find and format all uses of a word?



eed
12-21-2005, 06:08 PM
Hi, all,

I'm creating and formatting a Word document (based on a .dot template) from VBA.

I'd like to be able to find all instances of a word in the document and change the background color and font color of just that word. So, for example, every instance of the word "Yellow" should have the background changed to black and the font changed to yellow.

Using the VBA recorder, I can see the code Word uses to execute a Find and manipulate an individual found item... but I'm getting myself all confused about how I could write some sort of loop that would automatically search the whole document and change every instance. http://vbaexpress.com/forum/images/smilies/104.gif

Help is deeply appreciated!!!

~ eed

mdmackillop
12-21-2005, 06:25 PM
Hi eed
Might need a little tweaking for your needs but try this as a start.

Sub Wasp()

Dim Txt As String
Txt = InputBox("Text to highlight")

With Selection.Find
.ClearFormatting
Do While .Execute(FindText:=Txt, Forward:=True, _
Format:=True) = True
Selection.Range.HighlightColorIndex = wdBlack
Selection.Font.Color = wdColorYellow
Loop
End With
End Sub

eed
12-21-2005, 09:20 PM
Hey! That worked like a charm. I needed to reset the starting point to the appropriate bookmark and perform several loops looking for several specific words, plus add the proper reference to make it all work from Access, but all the modifications went quite smoothly. I'm including my final loop below in case (God knows why!) someone else is curious. So... Thanks!!!! :bigkiss:
objWord.Selection.GoTo What:=wdGoToBookmark, Name:="LongBlurbs"
With objWord.Selection.Find
.ClearFormatting
Do While .Execute(FindText:="Intermec", Forward:=True, _
Format:=True) = True
objWord.Selection.Range.HighlightColorIndex = wdYellow
objWord.Selection.Font.Color = wdColorRed
objWord.Selection.Font.Bold = True
Loop
End With

objWord.Selection.GoTo What:=wdGoToBookmark, Name:="LongBlurbs"
With objWord.Selection.Find
.ClearFormatting
Do While .Execute(FindText:="UNOVA", Forward:=True, _
Format:=True) = True
objWord.Selection.Range.HighlightColorIndex = wdBrightGreen
objWord.Selection.Font.Color = wdColorPink
objWord.Selection.Font.Bold = True
Loop
End With
~ eed

mdmackillop
12-22-2005, 02:21 AM
Happy to help,
Have a good Christmas:rudolph:
MD