View Single Post
 
Old 03-03-2018, 11:13 PM
poetofpiano poetofpiano is offline Windows 10 Office 2016
Novice
 
Join Date: Sep 2015
Posts: 25
poetofpiano is on a distinguished road
Default Loop to Collapse Paragraphs within Range Not Working

I have a document using the built-in headings styles of Heading1, Heading2, and Heading3 in several places, and within each of these headings are paragraphs that have an outline level so that I can collapse the paragraphs. I have marked each of these paragraphs by the text "(1)" without the quotation marks so that I can find them with VBA.

What I am trying to do is loop through all the paragraphs under a single Heading (be it Heading1, 2, or 3) and collapse the paragraphs under that heading so that I can see the content within the heading much easier. This is what I have so far:

Code:
Sub CollapseOutlinesWithinHeading()
'Go to beginning of currently selected heading 
Dim heading As Range
Set heading = Selection.GoTo(What:=wdGoToHeading, Which:=wdGoToPrevious)

'select the entire heading
    Dim headingLevel As Range
    ' headingLevel encompasses the region under the preceding heading
    Set headingLevel = Selection.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")

'loop through to collapse paragraphs marked by text "(1)"
Set oRng = Selection.Range
  With oRng.Find
    While .Execute(FindText:="(1)", Forward:=True)
      If .Found = True Then
        oRng.Paragraphs(1).CollapsedState = True
      End If
    Wend
  End With
End Sub
This works fine if the selected heading is the last heading in the document. My problem is when I am acting on a heading in the middle of the document. Even though the routine defines the .find range to be the selected heading, the routine disregards this and continues on searching to the end of the document, collapsing every paragraph marked with "(1)" from the start of the selected heading to the end of the document.

I have read at https://gregmaxey.com/word_tip_pages..._property.html that the .find property is very finicky, but none of the reasons it is finicky seem like they should be triggered in my routine. Can anyone help me make my version of the routine work, or must I resort to what the user at https://superuser.com/questions/8853...-defined-range did, which is to only loop the number of times that the match is found in the selection? If so, how would that best be written in this case?

Thank you so much for your help!
Reply With Quote