pianoman102
pianoman102

Reputation: 549

Find highlighted text, and modify it, VBA word

I have a large document that has been converted from a pdf and I am trying to do some cleanup on it. There are a few portions of text that have a text highlight, for example, if the bolded text had a highlight: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eu tempus mauris, sit amet ultricies massa. Phasellus rhoncus magna ac pharetra aliquam." I want to find every instance of a highlighted text, and essentially add a label to it and remove the highlight, like: "Lorem ipsum [label: dolor sit] amet, consectetur adipiscing elit. Sed eu tempus mauris, sit amet [label: ultricies] massa. Phasellus [label: rhoncus magna ac pharetra] aliquam."

I'm using VBA and have tried a number of variations of find. I was first trying to iterate paragraph by paragraph, but that got tedious. My most recent iteration looks like this, and seems to affect the entire document and adds the specified text at the beginning of the doc rather than replacing the highlight that is supposedly found with .Highlight = True:

Set curDoc = Documents.Open(filePath, Visible:=True)
with curDoc.Range.Find
    .Highlight = True
        Do While .Execute
            curDoc.Range.Text = "[label: " + curDoc.Range.Text + "]"
            curDoc.Range.HighlightColorIndex = wdNoHighlight
            curDoc.Range.Font.Color = wdAuto
        Loop
End With

Upvotes: 1

Views: 1643

Answers (2)

Timothy Rylatt
Timothy Rylatt

Reputation: 7850

Your code is failing because you haven't constructed it correctly. When you use .Find with a Range object Find redefines it to the range of the match. However, because of the way you have constructed your With statement curDoc.Range always points to the entire document.

The code below should get you going in the right direction.

With curDoc.Range
   .Find.Highlight = True
   Do While .Find.Execute
      .HighlightColorIndex = wdNoHighlight
      .Text = "[label: " & .Text & "]"
      .Font.Color = wdAuto
      .Collapse wdCollapseEnd
   Loop
End With

Upvotes: 2

Kin Siang
Kin Siang

Reputation: 2699

You may try the following method, if any bold text are found, then change the text as per you expected, please take note when you are looking other style of highlighted text, remember to turn it off like font.bold = false, else infinite loop will trigger:

Sub test()

Dim sentence As Range
Dim w As Range

For Each sentence In ActiveDocument.StoryRanges
    For Each w In sentence.Words
        If w.Font.Bold = True Then
            w.Text = "[Label: " + w.Text + "]"
            w.Font.Bold = False
            w.HighlightColorIndex = wdNoHighlight
            w.Font.Color = wdAuto
        End If
    Next
Next

End Sub

Upvotes: 0

Related Questions