Search & Replace in a table

P

PPL

Having positioned the cursor inside a table, The following code is intended
to work in the second column of a 2 col table and replace the word "From"
with an autotext entry called "Handoff from"
Problem is that I can not contain it to work ONLY inside the table. It works
through the entire document. Please - what am I doing wrong?

Any help would be appreciated.
TIA
Phil


'Replace From with Hand-off from in a 2 column table
Selection.Tables(1).Select
Selection.EndKey Unit:=wdLine
Selection.SelectColumn
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

With Selection.Find
.Text = "From"
.Forward = True
.MatchCase = True
.Wrap = False
.Execute
End With

While Selection.Find.Found
NormalTemplate.AutoTextEntries("Handoff from").Insert
Where:=Selection. _
Range, RichText:=True

Selection.Find.ClearFormatting
With Selection.Find
.ClearFormatting
.Text = "From"
.Forward = True
.MatchCase = True
.Wrap = wdFindStop
.Execute
End With

Wend
 
G

Greg Maxey

Phil,

You will need to change the autotext name, but try this:

Sub Test()
Dim oRng As Word.Range
Selection.Tables(1).Columns(2).Select
Set oRng = Selection.Range
With oRng.Find
.ClearFormatting
.Text = "From"
.Forward = True
.MatchCase = True
.Wrap = False
While .Execute
NormalTemplate.AutoTextEntries("HandOffFrom").Insert Where:=oRng,
RichText:=True
Wend
End With
End Sub
 
J

Jay Freedman

Hi Phil,

The trick to this is to check in each iteration whether the range of
the found text is inside the range of the table, using the .InRange
function. If the found range falls outside the table, you have to exit
the loop.

Besides that, you have a problem with running the find in a selected
column. The difficulty is that a column isn't (internally in Word) a
continuous chunk of text -- Word reads the table left to right and
then down, so the column is a discontinuous selection. So don't try
running the find in a selected column; just run the loop over the
whole table, and make the replacement only if it's in column 2.

Try it this way:

Dim TblRg As Range
Dim SrchRg As Range

'Replace From with Hand-off from in a 2 column table
Set TblRg = Selection.Tables(1).Range
Set SrchRg = TblRg.Duplicate

With SrchRg.Find
.ClearFormatting
.Text = "From"
.Forward = True
.MatchCase = True
.Wrap = wdFindStop

Do While .Execute
If Not (SrchRg.InRange(TblRg)) Then
Exit Do
End If

If SrchRg.Information(wdEndOfRangeColumnNumber) = 2 Then
NormalTemplate.AutoTextEntries("Handoff from").Insert _
Where:=SrchRg, RichText:=True
End If
SrchRg.Collapse wdCollapseEnd
Loop
End With

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 

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