I'm trying to tidy up documents by removing any replicate paragraph markers and have found that the last paragraph marker is non-standard. I'm using Find and Replace and because I don't know how many replicates I'm going to find, I need to use .Found and a Do loop to keep cycling round. See code below.
This works fine until it encounters a duplicate paragraph marker at the end of the document. In this situation Word 'finds' the duplicate paragraph marker but fails to replace it and so the code above gets stuck in an infinite loop. Try it - the same thing happens in this situation if you use the foreground Find and Replace for ^p^p and ^p respectively(but without the infinite loop!).
The only way I could get round this was by using the code below which keeps looping to see if the 2nd last character is a paragraph marker and delete if it is.
OK. Having provided both the problems and solution, does anyone know if there is a more elegant way around this? Or are there different arguments to use for the original find and replace?
Thanks in advance.
Code:
Sub Delete_Rep_ParaMarkers()
Dim Findstr As String
Dim Char As String
Dim ReplaceStr As String
Dim Rng As Range
Dim Notfound As Boolean
Set Rng = ActiveDocument.Content
Char = "^p" ' Or Chr(13)
ReplaceStr = Char
Findstr = "^p^p" ' Or Chr(13) & Chr(13)
Notfound = False
Do Until Notfound
Rng.Find.ClearFormatting
Rng.Find.Replacement.ClearFormatting
With Rng.Find
.Text = Findstr
.Replacement.Text = ReplaceStr
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
If .Found Then
Notfound = False
Else
Notfound = True
End If
End With
Loop
End Sub
The only way I could get round this was by using the code below which keeps looping to see if the 2nd last character is a paragraph marker and delete if it is.
Code:
Dim Rng As Range
Dim Dun As Boolean
Dun = False
Do
Set Rng = ActiveDocument.Range (Start:=ActiveDocument.Range.End - 2, End:=ActiveDocument.Range.End)
If Asc(Rng.Characters(1)) = 13 Then
Rng.Delete
Else
Dun = True
End If
Loop Until Dun
OK. Having provided both the problems and solution, does anyone know if there is a more elegant way around this? Or are there different arguments to use for the original find and replace?
Thanks in advance.