Search for any heading style RRS feed

  • Question

  • I'm writing a macro in which I need to search the document (which is one very long table) for the next heading. It doesn't matter which heading style, just whichever heading appears next in the document.
    Friday, June 23, 2017 9:32 PM

All replies

  • The following should work, from the current cursor position, provided there are no vertically merged cells in the table and the styles use the built-in heading style names.

    Sub NextHeading()
    Dim oRng As Range
    Dim oCell As Cell
    Dim iRow As Integer
        On Error GoTo err_Handler
        If Selection.Information(wdWithInTable) = True Then
            iRow = Selection.Tables(1).Rows.Count
            Set oRng = Selection.Range
            For Each oCell In oRng.Rows(1).Range.Cells
                If oCell.Range.Style Like "Heading*" Then
                    If Not oCell.Range.Rows(1).Index = iRow Then
                        oRng.Start = oCell.Range.Rows(1).Range.Next.Rows(1).Cells(1).Range.Start
                        Exit For
                    End If
                End If
            Next oCell
            oRng.Start = oRng.Rows(1).Cells(1).Range.Start
            oRng.End = Selection.Tables(1).Range.End
            For Each oCell In oRng.Cells
                If oCell.Range.Style Like "Heading*" Then
                    Exit For
                End If
            Next oCell
        End If
        Set oRng = Nothing
        Set oCell = Nothing
        Exit Sub
        GoTo lbl_Exit
    End Sub

    Graham Mayor - Word MVP

    Saturday, June 24, 2017 11:54 AM