Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Find and Replace in just the selection

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...