Will not Find/Replace at end of document?

E

Ed

I have a text "banner" that repeats throughout my document. I do a
Find/Replace to delete this banner (replace it with "") using the code
below, which works fine - except it won't Find/Replace the banner at the
very end of the document. The document is text-only, with each line ending
in a paragraph mark. The string being searched for consists of three
lines/paragraphs. It is the first three paragraphs of the doc. At the end
of the document, this would also include the very last paragraph mark in the
doc.

If there is a better way to accomplish this, I would appreciate any help.

Ed

Set doc1 = Documents.Open(FileName:=strFldr & "\" & strDump)
Set rngDoc = doc1.Range

' Check for banner
Set rngTIR = doc1.Paragraphs(1).Range
rngTIR.SetRange _
Start:=doc1.Paragraphs(1).Range.Start, _
End:=doc1.Paragraphs(3).Range.End

If rngTIR.Words(4).Text = "HERE" Then
strUncl = rngTIR.Text
End If

' If header exists, delete it everywhere
If strUncl <> "" Then
Debug.Print strUncl
Set rngTIR = rngDoc
rngTIR.Find.Execute _
FindText:=strUncl, _
ReplaceWith:="", _
Replace:=wdReplaceAll
End If
 
D

Dave Lett

Hi Ed,

I've shortened your routine some, and added a new conditional to see if the
last paragraph is only a paragraph mark. If so, then the routine also
deletes that range:

Set doc1 = Documents.Open(FileName:=strFldr & "\" & strDump)
Set rngDoc = doc1.Range
Set rngTir = doc1.Paragraphs(1).Range
rngTir.SetRange _
Start:=doc1.Paragraphs(1).Range.Start, _
End:=doc1.Paragraphs(3).Range.End
If rngTir.Words(4).Text = "HERE " Then
rngDoc.Find.Execute _
FindText:=rngTir.Text, _
ReplaceWith:="", _
Replace:=wdReplaceAll
End If
''' test if the last paragraph is empty
With ActiveDocument.Paragraphs.Last.Range
If .Characters.Count = 1 Then
.delete
End If
End With

HTH,
Dave
 

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