0
votes

I am trying to delete everything in a specific word document that is highlighted in a certain color, in this example; wdYellow. I have some code below that opens the Word document, tries to find where highlighting occurs and deletes it accordingly.

Set wrdApp = New Word.Application
strFilePath = ThisWorkbook.Path
Set wrdDoc = wrdApp.Documents.Add(strFilePath & "\test.docx")

With wrdDoc.Content.Find
    If .Highlight = wdYellow Then
        .text = ""
    End If
End With

wrdDoc.SaveAs (strFilePath & "\test.docx")
wrdApp.Quit

Set wrdDoc = Nothing
Set wrdApp = Nothing

So this code works to an extent... It doesn't actually find any highlights with wdYellow, so it will never reach .text = "". But other than that, it runs through it just fine. I believe the error to be with the With wrdDoc.Content.Find section. Can anyone help me out?

2
Word's find doesn't work with If in this manner. I suggest you try in the Word UI (Ctrl+H) to find the highlight color and record a macro to get the basics. Also, you can try using Replace and replace with nothing (empty string - no entry in the Replace box). Not sure whether that will work with highlighting, though... If it doesn't work, get as far as you can based on the recorded macro, then update your post with that and describe how it's not doing the job. - Cindy Meister

2 Answers

0
votes

Try this one:

Dim wrdApp As Object

Set wrdApp = CreateObject("Word.Application")
strFilePath = ThisWorkbook.Path
wrdApp.Visible = True
wrdApp.Documents.Open (strFilePath & "\test.docx")
wrdApp.Selection.Find.Highlight = True
wrdApp.Selection.Find.Execute Replace:=wdReplaceAll

With this code you will get all the highlighted text in your file. .Highlight is a boolean value, so it can not be wdYellow. If you need to check color, use Range.HighlightColorIndex property.

I can not make comments, sorry.

Hope it helps.

0
votes

The macro recorder gives the following, which successfully replaces all text highlighted yellow. You can integrate it into your code framework.

Sub DeleteHighlightedText()
'
' DeleteHighlightedText Macro
'
'
    ActiveDocument.content.HighlightColorIndex = wdYellow
    With Selection.Find
        .ClearFormatting
        .Highlight = True
        .Replacement.ClearFormatting
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchByte = False
        .CorrectHangulEndings = False
        .HanjaPhoneticHangul = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub