View Single Post
 
Old 11-10-2023, 04:46 AM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,601
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

There are better ways than the simple fix above.



For one, if your document has a thousand or say a million paragraphs, it would be inefficient to evaluate each one to see if it was the last one. So, since you now know that there is no next paragraph following the last paragraph of a document you could use an error handler:


Code:
Sub A()
  Dim oPar As Paragraph
  For Each oPar In ActiveDocument.Paragraphs
    'If oPar.Range.ParagraphFormat.Alignment = wdAlignParagraphRight Then
      oPar.Style = "Body Text"
      On Error GoTo Err_Handler
      oPar.Next.Style = "Body Text"
    'End If
  Next oPar
lbl_Exit:
  Exit Sub
Err_Handler:
  If Err.Number = 91 Then
    If oPar.Range.End = ActiveDocument.Range.End Then
      'You know this error will occur so it is not an issue
      
    Else
      MsgBox Err.Number & " " & Err.Description
    End If
  Else
     MsgBox Err.Number & " " & Err.Description
  End If
  Resume lbl_Exit
End Sub

or you could adjust your processing range so you never reach the last paragraph:


Code:
Sub B()
Dim oRng As Range
  Dim oPar As Paragraph
  Set oRng = ActiveDocument.Range
  oRng.End = ActiveDocument.Range.Paragraphs.Last.Previous.Range.End
  For Each oPar In oRng.Paragraphs
    If oPar.Range.ParagraphFormat.Alignment = wdAlignParagraphRight Then
      oPar.Style = "Body Text"
      oPar.Next.Style = "Body Text"
    End If
  Next oPar
lbl_Exit:
  Exit Sub
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote