View Single Post
 
Old 10-07-2015, 09:29 AM
cyraxote cyraxote is offline Windows 7 64bit Office 2013
Novice
 
Join Date: Sep 2015
Location: Essex, MD
Posts: 24
cyraxote is on a distinguished road
Default compare each paragraph with the preceding paragraph

I'm writing a macro to check the style of each paragraph against the previous. (I know that there's a way to do this using the paragraphs object, which apparently has a mysterious "previous paragraph" parameter, but I can't figure it out.) Here's what I have:

Code:
Sub fix2textparas()

Dim Para1, Para2 As String

Selection.HomeKey Unit:=wdStory
Selection.Find.Style = ActiveDocument.Styles("TEXT")
With Selection.Find
    .Forward = True
    .Wrap = wdFindStop
    .Format = True
    .MatchWildcards = True
    .Execute
End With

Do While Selection.Find.Found = True
    Para1 = Selection.Paragraphs(1).Style
    Selection.Next(Unit:=wdParagraph, Count:=1).Select
    Para2 = Selection.Paragraphs(1).Style
    If Para1 = "TEXT" And Para2 = "TEXT" Then
        With Selection.Paragraphs(1)
            .Range.Select
            .Style = "TEXT IND"
            .Range.HighlightColorIndex = wdYellow
        End With
        With Selection.ParagraphFormat
            .SpaceBefore = 0
            .SpaceBeforeAuto = False
            .SpaceAfter = 6
            .SpaceAfterAuto = False
            .LineSpacingRule = wdLineSpaceSingle
        End With
    End If
    Selection.Collapse Direction:=wdCollapseStart
Loop
End Sub
The problem is that I get an error when I get to the last paragraph and "Selection.Next(Unit:=wdParagraph, Count:=1).Select" tries to move forward. I didn't even want to use this method, but the following methods would not work for reasons I can't even begin to grasp:

Code:
With Selection   
    .Expand Unit:=wdParagraph
End With
Code:
Selection.MoveRight Unit:=wdParagraph, Count:=1, Extend:=wdExtend
The last gives Error 4120 Bad parameter.

I know that I could probably just trap the error, but it seems like there should be a way to do this without having to do so.

The rules for the styles in my document are:
  1. There should never be two consecutive paragraphs with style "TEXT"; if there are, the second should be changed to "TEXT IND."
  2. "TEXT IND" always follows "TEXT"
This means that any 3 paragraphs should never be:

TEXT
TEXT
TEXT IND

or

TEXT IND
TEXT
TEXT IND

The macro only deals with the first of these at the moment, and there are criteria for "TEXT" that are not needed here.

Any help would be great.


Thanks!
Reply With Quote