Thread: [Solved] VBA IF Statement Help
View Single Post
 
Old 03-15-2024, 12:33 PM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,617
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

Your error occurs because you are trying to evaluate a field code in paragraph 1.3 and that field does not exist in paragraph 1.3
Revised code. Only evaluate field if field is present.

Code:
       Sub A()
Dim oPara As Paragraph
Dim Rng As Range
  On Error GoTo Err_Handler:
  For Each oPara In ActiveDocument.Paragraphs 'Highlights missing punctuation at end of paragraphs
    With oPara.Range
      If .Information(wdWithInTable) Or .Font.AllCaps Or .Characters.First.Font.Bold Or Len(.Text) < 3 Then
        GoTo NextFor
      Else
        If Not .Characters.Last.Previous Like "*[.!?:;,]" Then
          Select Case True
            Case .Characters.Last.Previous.Fields.Count = 1
              If Not .Characters.Last.Previous.Fields(1).Result = "]" Then
                .Words.Last.Previous.Words(1).HighlightColorIndex = wdPink
              End If
            Case Else
              If Not .Characters.Last.Previous Like "]" Then
                .Words.Last.Previous.Words(1).HighlightColorIndex = wdPink
              End If
          End Select
        End If
        Select Case .Words.Last.Previous.Words(1)
          Case "and", "but", "or", "then", "plus", "minus", "less", "nor"
            Set Rng = .Words.Last    '.Previous.Words(1)
            Rng.MoveStartUntil cSet:=" " & Chr(160), Count:=-10
            Set Rng = Rng.Characters.First.Previous.Previous
            If Rng.Text = ";" Then
              'if oPara ends with these words and have semi-colon before them do nothing no highlight else
              .Words.Last.Previous.Words(1).HighlightColorIndex = wdNoHighlight
              If Rng.Text = "," Then
                'if oPara ends with these words and have semi-colon before them do nothing no highlight else
                .Words.Last.Previous.Words(1).HighlightColorIndex = wdPink
              End If
            End If
          Case Else
        End Select
      End If
    End With
NextFor:
  Next oPara
lbl_Exit:
  Exit Sub
Err_Handler:
  MsgBox Err.Number & " - " & Err.Description
  oPara.Range.Select
  Resume
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote