Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace in just the selection

Tags:

ms-word

vba

I have the following macro. It changes numbers of the form x.x to x,x. It was recorded and I added the IF statement to make sure a text is selected to prevent the user from doing it on the whole document.

 Sub fixComma()
    '
    ' fixComma Macro
    '
    '
      If (Selection.Start <> Selection.End) Then
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        Selection.Find.Replacement.LanguageID = wdEnglishUS
        With Selection.Find
            .Text = "([0-9]).([0-9])"
            .Replacement.Text = "\1,\2"
            .Forward = True
            .Wrap = wdFindAsk
            .Format = True
            .MatchCase = False
            .MatchWholeWord = False
            .MatchKashida = False
            .MatchDiacritics = False
            .MatchAlefHamza = False
            .MatchControl = False
            .MatchByte = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
        End With

        Selection.Find.Execute Replace:=wdReplaceAll
         Else
           MsgBox "Nothing is selected, Macro terminated"
        End If
    End Sub

The problem is it is changing the whole document and not just the selection.

like image 713
Moha the almighty camel Avatar asked Dec 08 '25 18:12

Moha the almighty camel


1 Answers

Changing

 Selection.Find.Execute Replace:=wdReplaceAll

to

 Selection.Find.Execute Replace:=wdReplaceOne

Will get it so the first instance of x.x in a selection will change to x,x and not the whole document.

Edit: if you want all items in a selected area only to change then keep:

Selection.Find.Execute Replace:=wdReplaceAll

But change

.Wrap = wdFindAsk

to

.Wrap = wdFindStop
like image 139
mrlemmer11 Avatar answered Dec 11 '25 09:12

mrlemmer11