当前位置: 动力学知识库 > 问答 > 编程问答 >

vba - 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

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: