Pat
Pat

Reputation: 361

How to perform a selective extraction of text highlighted in yellow from an MS Word document?

I am trying to write a VB script that extracts all text passages highlighted in yellow from a given MS Word document. My code seems >>almost<< to be working ... but I have not been able to restrict the text export to sections highlighted in yellow only. Please note the script has to be selective for highlight colour in case the document contains highlights in several colours.

Sub FindHighlightedText()

    'Get current working directory.
    Dim pwd As String
    pwd = ActiveDocument.Path

    Dim Name As String
    Name = pwd & "\Output.txt"

    ' Create a filehandle and open the output file.
    handle = FreeFile()
    Open Name For Output As #handle

    With ActiveDocument.Range.Find

        .ClearFormatting
        .Highlight = True
        .Forward = True

        'I THINK THE PROBLEM IS HERE!!
        If .Parent.HighlightColorIndex = wdYellow Then
              print #handle, .Parent.Text & vbNewLine
        End If

    End With


    ' Close the output filehandle.
    Close #handle

End Sub

Upvotes: 0

Views: 1422

Answers (1)

Tim Williams
Tim Williams

Reputation: 166196

This might help

Sub Macro1()

    With Selection.Find
        .Highlight = True
        .Wrap = wdFindContinue
        .Format = True
    End With

    Do While Selection.Find.Execute()

        If Selection.Range.HighlightColorIndex = wdYellow Then
             Debug.Print Selection.Range.Text
        End If

    Loop

End Sub

Upvotes: 2

Related Questions