FanBan
FanBan

Reputation: 35

Only search text user has selected

I'm used to working with Selection.WholeStory, but now have a macro where I make a lot of search and replace operations. I only want the module to search and replace in the selection the user has selected before running the macro.

How can I do this? I've tried Selection.Text, but Word tells me this is invalid use of the Text property.

ADDED: My module starts like this

Sub Bibliography()

With ActiveDocument
        .TrackRevisions = False
        .PrintRevisions = False
        .ShowRevisions = False
End With
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

By not specifying the selection object I should get only the selection the user has already made before running the macro. But this doesn't seem to work. For instance, the code below changes the occurences in the entire document, not just in the selection made by the user

With Selection.Find
    .Text = "%"
    .Replacement.Text = " %"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

Upvotes: 2

Views: 3643

Answers (1)

Kazimierz Jawor
Kazimierz Jawor

Reputation: 19077

In my opinion you only need to change one line:

.Wrap = wdFindContinue

into this one:

.Wrap = wdFindStop

But keep also in mind that if nothing is selected (single cursor is blinking) than your code will run for whole document. To avoid such a thing you could try either Mehow solution (not sure if it will work) or you could add simple if statement at the beginning:

If Selection.Range.Start = Selection.Range.End Then
    MsgBox "Select something, please!"
    Exit Sub
End If

Upvotes: 5

Related Questions