View Single Post
 
Old 11-14-2022, 12:32 AM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,176
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

Whenever you are iterating through objects it is not good to delete any objects that are in the remainder of that collection.

You can fix it by moving backwards so that any deletions don't matter because the next loop only hits paragraphs you haven't changed yet.
Code:
Private Sub secHeading()
  Dim para As Paragraph, iPar As Long

  For iPar = ActiveDocument.Paragraphs.Count - 1 To 1 Step -1
    Set para = ActiveDocument.Paragraphs(iPar)
    If Trim(UCase(para.Range.Words(1))) = "RCW" Then
      With para.Range
          .Collapse (wdCollapseEnd)
          .Move Unit:=wdCharacter, Count:=-1
          .Delete
          .InsertAfter ("  --  ")
          .Style = "Heading 1"
      End With
    End If
  Next
End Sub
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote