Find and replace multiple words...

B

Bill Foley

Trying to find a VBA solution to search for several specific words and
underline them (AND, IF, THEN, WHEN). It must match the case since these
are the only ones I wanted underlined. Also want to search for RECORD and
bold it.

TIA!

Bill
 
L

larrysulky

Try this, Bill:

Sub HiliteSyntax()

Selection.HomeKey Unit:=wdStory

With Selection.Find
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
.Replacement.Font.Underline = wdUnderlineWords
End With

With Selection.Find
.ClearFormatting
.Text = "<AND>"
.Replacement.Text = "^&"
.Execute Replace:=wdReplaceAll
End With

With Selection.Find
.ClearFormatting
.Text = "<IF>"
.Replacement.Text = "^&"
.Execute Replace:=wdReplaceAll
End With

With Selection.Find
.ClearFormatting
.Text = "<THEN>"
.Replacement.Text = "^&"
.Execute Replace:=wdReplaceAll
End With

With Selection.Find
.ClearFormatting
.Text = "<WHEN>"
.Replacement.Text = "^&"
.Execute Replace:=wdReplaceAll
End With

Selection.Find.Replacement.ClearFormatting
Selection.Find.Font.Underline = wdUnderlineNone
With Selection.Find
.ClearFormatting
.Text = "<RECORD>"
.Replacement.Text = "^&"
.Replacement.Font.Bold = True
.Execute Replace:=wdReplaceAll
End With

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

End Sub
 
H

Helmut Weber

Hi Bill,

just another one:

Sub Test700()
Dim rDcm As Range
Dim x As Long
Dim arrU() As String
Dim arrB() As String
arrU = Split("AND,IF,THEN,WHEN", ",") ' underline
arrB = Split("RECORD", ",") ' bold
For x = 0 To UBound(arrU)
Set rDcm = ActiveDocument.Range
With rDcm.Find
.Text = "<" & arrU(x) & ">"
.MatchWildcards = True
.Replacement.Font.Underline = wdUnderlineSingle
.Replacement.Text = "^&"
.Execute Replace:=wdReplaceAll
End With
Next
For x = 0 To UBound(arrB)
Set rDcm = ActiveDocument.Range
With rDcm.Find
.Text = "<" & arrB(x) & ">"
.MatchWildcards = True
.Replacement.Font.Bold = True
.Replacement.Text = "^&"
.Execute Replace:=wdReplaceAll
End With
Next
ActiveDocument.Range(0, 0).Select
End Sub

--

Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Vista Small Business, Office XP
 

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