Forum Discussion

Eskimo007's avatar
Eskimo007
Copper Contributor
Feb 26, 2025
Solved

Need a macro to create a subdocument

I have a document with some lines that contain a string, say <astring>.  I would like to have a macro that would parse the document, and create a new document that only contains the lines that have <...
  • Doug_Robbins_Word_MVP's avatar
    Mar 08, 2025

    Use a macro containing the following code

    Sub MakeSubDoc()
    Dim source As Document
    Dim target As Document
    Dim str As String
    Dim rngstr As Range
    Set source = ActiveDocument
    Set target = Documents.Add
    source.Activate
    str = InputBox("Insert the text to be found.")
    Selection.HomeKey wdStory
    Selection.Find.ClearFormatting
    With Selection.Find
        Do While .Execute(FindText:=str, MatchWildcards:=False, MatchCase:=True, Wrap:=wdFindStop, Forward:=True) = True
            Set rngstr = Selection.Range.Bookmarks("\line")
            target.Range.InsertAfter rngstr & vbCr
            Selection.Collapse wdCollapseEnd
        Loop
    End With
    target.Activate
    End Sub

Resources