PDA

View Full Version : Solved: find comand



Drifter518
11-24-2008, 09:50 AM
Hi Everyone,

I'm trying to do a simple find macro but have question if word can hand it, I am trying to find the statement "Table BM_1" but I only want to find BM_1, it keeps finding "Table BM_10, Table BM_11 ....." Is there a way to make it only find BM_1?? it seems simple but I can't seem to figure it out.

Thanks

CreganTur
11-24-2008, 10:35 AM
Welcome to the forum- always good to see new members.

Well, Tale BM_10 and _11 are valid returns from find, since they both cotnain Table BM_1

I would suggest explicitly adding a space to the end: "Table BM_1 "

That should work... as long as that specific entry in your Doc has a space after it...:dunno

Drifter518
11-24-2008, 10:50 AM
Thanks I kind of figured that was the only way around it I was trying to avoid it but I'll have to add some extra characters. :) Thanks

fumei
11-24-2008, 12:23 PM
Hmmmm. No, it is not the only way around it. This is simply a matter of using logic. What is the issue?

You want:

Table BM_1 but not Table BM_10, or Table BM_105, or Table BM_12.

The problem is that .Find will find all "Table BM_1", and that is true. So....

1. expand the .Found range to the whole word (this means explicitly getting Table BM_12, or Table BM_14, or Table BM_1054)

2. testing the last two characters to see if they are explicitly "_1". In other words, Table BM_12 would fail as the last two characters are "12", Table BM_10 would fail as the last two characters are "10", etc. etc. The ONLY Found that would not fail is....."_1".

Like this:

Dim r As Range
Set r = ActiveDocument.Range
With r.Find
Do While .Execute(FindText:="Table BM_1", _
Forward:=True) = True
r.Expand Unit:=wdWord
If Right(r.Text, 2) = "_1" Then
r.HighlightColorIndex = wdBrightGreen
End If
r.Collapse 0
Loop
End With

Demo attached. Click "Just Table1" on the top toolbar. Only "Table BM_1" gets highlighted.

I did it as a highlight because I have no idea what you are actually doing with "Table BM_1".

fumei
11-24-2008, 12:48 PM
Just as a precautionary note...

With this kind of action on the .Found range of a .Find, you must, repeat MUST, collapse the range after each iteration! The:
r.Collapse 0



Otherwise you will go into an infinite loop...and you don't want that.

RULE: any changes to the .Start or .End of the original .Found range (of a .Find) requires a Collapse. Changes to content does not.

This changes the range:
Do While .Execute(FindText:="Table BM_1", _
Forward:=True) = True
r.Expand Unit:=wdWord ' BECAUSE this here
If Right(r.Text, 2) = "_1" Then
r.HighlightColorIndex = wdBrightGreen
End If
r.Collapse 0 ' REQUIRES this
Loop


This does NOT:
Do While .Execute(FindText:="Table BM_1", _
Forward:=True) = True
If Right(r.Text, 2) = "_1" Then
r.HighlightColorIndex = wdBrightGreen
End If
Loop