Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

word vba: select text between headings

Tags:

ms-word

vba

I have a word document in which I would like to select the full text of the heading starting with enumeration 2.3.1 until (not included) the heading 2.3.2 or [End of File]. If there are 'smaller' subsections or pictures or tables in between, they should also be selected.

PS: Example:

... 2.2 Blah Blah 2.3 Blubb Blubb [Start Selection] 2.3.1 Important1 Important2 [Picture: Important3] [Table: Important4] 2.3.1.1 Important 5 Important 6 [Stop Selection] 2.3.2 Blieh

I have experimented with navigating through every paragraph, but this is quite slow. I need this feature to copy the selection afterwards (I already know how to do that ;-)).

Thank you very much for help!

Jan

like image 278
user1729603 Avatar asked Dec 14 '25 06:12

user1729603


1 Answers

This seems to work well.
Adjust the format setting so that it finds '2.3.1' etc. only in that given format type.

Sub Macro1()
    Selection.WholeStory
    Selection.Collapse wdCollapseStart

    Selection.Find.ClearFormatting
    Selection.Find.Style = ActiveDocument.Styles("Caption 1")
    With Selection.Find
        .Text = "2.3.1"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = True
    End With
    Selection.Find.Execute
    Selection.Collapse wdCollapseStart

    Dim r1 As Range
    Set r1 = Selection.Range

    ' keep format settings, only change text
    Selection.Find.Text = "2.3.2"
    If Selection.Find.Execute Then
        Selection.Collapse wdCollapseStart
    Else
        Selection.WholeStory
        Selection.Collapse wdCollapseEnd
    End If
    Dim r2 As Range
    Set r2 = ActiveDocument.Range(r1.Start, Selection.Start)
    r2.Select

End Sub
like image 128
KekuSemau Avatar answered Dec 16 '25 18:12

KekuSemau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!