首页 > 解决方案 > 通过 Excel 宏删除 Word 文档中所有突出显示的文本

问题描述

在此示例中,我试图删除以某种颜色突出显示的特定 word 文档中的所有内容;wdYellow. 我在下面有一些代码可以打开 Word 文档,尝试查找突出显示的位置并相应地删除它。

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

所以这段代码在一定程度上有效......它实际上并没有找到 wdYellow 的任何亮点,所以它永远不会达到 .text = "". 但除此之外,它运行得很好。我认为错误与该With wrdDoc.Content.Find部分有关。谁能帮我吗?

标签: excelvbams-word

解决方案


试试这个:

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

使用此代码,您将获得文件中所有突出显示的文本。.Highlight 是一个布尔值,所以它不能是 wdYellow。如果您需要检查颜色,请使用Range.HighlightColorIndex property

我不能发表评论,对不起。

希望能帮助到你。


推荐阅读