Need to find a phrase with total match

C

cyberdude

Hi,

I need to write a macro to find the exact match of a phrase. For
example, I need to find "David Dyson" in the following paragraph:

He is David Dyson. David Dyso is a famous man in country X. David
Dysonn is a merchant. The father of David Dyson is Peter Dyson.

So, I should find two exact matches of "David Dyson" in the above (One
phrase is in "He is David Dyson.". The other phrase is "The father of
David Dyson is..."). May I ask how to write the VBA code to do the
search? Thanks.

Mike
 
J

Jean-Guy Marcil

cyberdude said:
Hi,

I need to write a macro to find the exact match of a phrase. For
example, I need to find "David Dyson" in the following paragraph:

He is David Dyson. David Dyso is a famous man in country X. David
Dysonn is a merchant. The father of David Dyson is Peter Dyson.

So, I should find two exact matches of "David Dyson" in the above (One
phrase is in "He is David Dyson.". The other phrase is "The father of
David Dyson is..."). May I ask how to write the VBA code to do the
search? Thanks.

Normally we would use the "Match Whole Word" option in the "More..." options
of the "Find" dialog, but this option cannot be used when you have more than
one word.

So, my workaround is to check if the character immediately before the first
character ("D") and the one immediately after the last ("n") are not letters.
If they are not letters, then we have a match.

Try this to see if it gives you joy:


Option Explicit

Sub FindText()

Dim strText As String
Dim lngCount As Long
Dim lngEnd As Long
Dim rngFind As Range

strText = "David Dyson"
lngCount = 0
Set rngFind = Selection.Range
lngEnd = rngFind.End

With rngFind.Find
.Text = strText
.Wrap = wdFindStop
Do While .Execute
If Not rngFind.Characters.First.Previous Like "[A-z]" _
And Not rngFind.Characters.Last.Next Like "[A-z]" Then
lngCount = lngCount + 1
End If
rngFind.Start = rngFind.End
rngFind.End = lngEnd
Loop
End With

If lngCount > 0 Then
MsgBox """" & strText & """ was found " _
& lngCount & " times in the current selection.", _
vbInformation, "Search result for " & strText
Else
MsgBox """" & strText & """ was not found " _
& "in the current selection.", _
vbInformation, "Search result for " & strText
End If

End Sub
 
K

Klaus Linke

Or you could use a wildcard search looking for "<David Dyson>".
The <angle brackets>, called "word anchors", match only at the start (<) and
end (>) of words.

Regards,
Klaus
 

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