Reactor4
Reactor4

Reputation: 111

How can I search for a selected word in the entire document and highlight it?

I am not familiar with VBA at all.

I want to search for text I select (rather than a given list of words or typing that text in a box), and then change its format (preferably make it bold or change its color).

I tried to change a few macros that I found.

Upvotes: 0

Views: 812

Answers (2)

macropod
macropod

Reputation: 13515

The VBA code for this can be rather simple. For example:

Sub MakeBold()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Replacement.Font.Bold = True
    .Text = Selection.Text
    .Replacement.Text = "^&"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .Execute Replace:=wdReplaceAll
  End With
End With
Application.ScreenUpdating = True
End Sub

For PC macro installation & usage instructions, see: http://www.gmayor.com/installing_macro.htm

For Mac macro installation & usage instructions, see: https://wordmvp.com/Mac/InstallMacro.html

Upvotes: 2

ASH
ASH

Reputation: 20342

This will do what you want. Copy/paste into your VB editor window.

Sub HighlightWords()

Dim Word As Range
Dim WordCollection(2) As String
Dim Words As Variant

'Define list.
'If you add or delete, change value above in Dim statement.
WordCollection(0) = "you"
WordCollection(1) = "or"
WordCollection(2) = "Word document"

'Set highlight color.
Options.DefaultHighlightColorIndex = wdYellow
'Clear existing formatting and settings in Find feature.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
'Set highlight to replace setting.
Selection.Find.Replacement.Highlight = True
'Cycle through document and find words in collection.
'Highlight words when found.

For Each Word In ActiveDocument.Words
    For Each Words In WordCollection
        With Selection.Find
        .Text = Words
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False

        End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Next
Next

End Sub

Before:

enter image description here

After:

enter image description here

Upvotes: 0

Related Questions