0
votes

In a long Word document I'd like to do the following:

Find all 'Heading 2' styles paragraphs, and IF those headings are not worded "Notes" then apply a certain style to the immediately following paragraph.

Here's my code:

Dim oPara As Paragraph
    For Each oPara In ActiveDocument.Paragraphs
        If oPara.Style = "Heading 2" And oPara.Range.Text <> "Notes" Then
            oPara.Range.Next(Unit:=wdParagraph, Count:=1).Select
           Selection.Style = "Normal"
        End If
    Next oPara

However, the paragraphs worded "Notes" are not excluded from the procedure so those following them also get converted to style "Normal". I'm not even sure oPara.Range.Text actually retrieves the wording of the paragraph.

Thank you.

3

3 Answers

0
votes

Try like this:

Dim oPara As Paragraph

For Each oPara In ActiveDocument.Paragraphs
    If oPara.Style = "Heading 2" And Replace(oPara.Range.Text, Chr(13), "") <> "Notes" Then
        oPara.Range.Next(Unit:=wdParagraph, Count:=1).Select
       Selection.Style = "Normal"
    End If
Next oPara

It seems that Word includes a carriage return Chr(13) after the header text, so when checking if the header text is "Notes", the carriage return must be removed.

0
votes

The most efficient way of finding all the instances of 'Heading 2' is to use Find. You can then test the text of the found range and if it meets your criteria apply the style to the following paragraph.

Sub FormatAfterHeading()
   Dim findRange As Range
   Set findRange = ActiveDocument.Content
   With findRange.Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Text = ""
      .Style = ActiveDocument.Styles(wdStyleHeading2)
      .Forward = True
      .Format = True
      .Wrap = wdFindStop
      Do While .Execute = True
         If InStr(findRange.Text, "Notes") > 0 Then
            'do nothing
         Else
            findRange.Next(wdParagraph, 1).Style = wdStyleNormal
         End If
         findRange.Collapse wdCollapseEnd
      Loop
   End With
End Sub
0
votes

I agree with Timothy. The following is faster still - and simpler. It's also more reliable, since Timothy's code matches on 'Notes' anywhere in the paragraph instead of 'Notes' being the whole of the paragraph text.

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = ""
    .Style = ActiveDocument.Styles(wdStyleHeading2)
    .Forward = True
    .Format = True
    .Wrap = wdFindStop
  End With
  Do While .Find.Execute = True
    If .Text <> "Notes" & vbCr Then .Next(wdParagraph, 1).Style = wdStyleNormal
    .Collapse wdCollapseEnd
  Loop
End With
Application.ScreenUpdating = True
End Sub