Search only works when text is blocked

M

Mike

I'm trying to write a macro that will find all instances
of a word and add a comment to it. The code below works,
but only if I highlight all my text with my mouse. What am
I doing wrong?
Thanks!

Sub addComment()
Selection.Find.ClearFormatting
With Selection.Find
.Text = "hello"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With

Do While Selection.Find.Execute
Selection.Comments.Add Range:=Selection.Range, _
Text:="This is my comment!"
Loop
End Sub
 
M

Mike

Wait, I lie - it searches only words that are ahead of the
cursor. I assume that the problem therefore lies in
..Forward = "True"
But what should be in its place? I don't want it to keep
going round forever. Thanks!
-M
 
M

Mark Tangard

Hi Mike,

You can fix that in a few different ways. One of the quieter
ones is to use a Range rather than the Selection. (It doesn't
move your cursor):

Dim r As Range
Set r = ActiveDocument.Range
With r.Find
.Text = "hello"
.Forward = True
.Wrap = wdFindStop
.MatchWholeWord = True
Do While .Execute
ActiveDocument.Comments.Add Range:=r, _
Text:="This is my comment!"
Loop
End With
 
M

Mike

Thank you!
-----Original Message-----
Hi Mike,

You can fix that in a few different ways. One of the quieter
ones is to use a Range rather than the Selection. (It doesn't
move your cursor):

Dim r As Range
Set r = ActiveDocument.Range
With r.Find
.Text = "hello"
.Forward = True
.Wrap = wdFindStop
.MatchWholeWord = True
Do While .Execute
ActiveDocument.Comments.Add Range:=r, _
Text:="This is my comment!"
Loop
End With

--
Mark Tangard, Microsoft Word MVP
Please reply only to the newsgroup, not by private email.
Note well: MVPs do not work for Microsoft.
"Life is nothing if you're not obsessed." --John Waters


.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top