You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改C#代码实现仅查找并删除Word文档中的高亮文本?

How to Modify the Code to Delete Only Highlighted Text in Word

Got it, let's tweak your existing code to target only highlighted text (regardless of what the text says) instead of searching for the specific word "Family". Here's the revised version with key improvements explained:

using Microsoft.Office.Interop.Word;

public void DeleteAllHighlightedText()
{
    const string filePath = "D:\\COM16_Duke Energy.doc";
    var word = new Application { Visible = true };
    
    try
    {
        var doc = word.Documents.Open(filePath);
        var range = doc.Range();
        
        // Clear any pre-existing formatting rules from the find operation
        range.Find.ClearFormatting();
        
        // Configure the find to target text with ANY highlighting (works for all highlight colors)
        range.Find.Highlight = true;
        
        // Loop until no more highlighted text is found
        while (range.Find.Execute())
        {
            // Delete the matched highlighted range directly (no need to select it first)
            range.Delete();
            
            // Reset the search range to the remaining part of the document
            // This prevents missing matches after deletions shift the document structure
            range = doc.Range(range.End, doc.Content.End);
        }
        
        // Save the changes (remove this line if you want to manually save or use SaveAs)
        doc.Save();
        doc.Close();
    }
    finally
    {
        // Ensure Word quits even if an error occurs (avoids orphaned background processes)
        word.Quit(true, Type.Missing, Type.Missing);
    }
}

Key Changes Explained:

  • Removed specific text matching: We got rid of range.Find.Text = "Family"; because we don't care about the content anymore—only the highlight formatting.
  • Added highlight targeting: range.Find.Highlight = true; tells Word's find engine to locate any text that has a highlight applied (this works for all highlight colors, not just a specific one).
  • Added error safety: The try/finally block ensures Word will close properly even if something goes wrong during the process (no more stuck Word.exe processes in Task Manager!).
  • Fixed range handling: After deleting a range, we reset the search range to start right after the deleted text. This prevents the find operation from skipping matches or looping infinitely as the document content shifts.
  • Optional save: The doc.Save() line persists your changes—you can replace this with doc.SaveAs2() if you want to save to a new file instead of overwriting the original.

内容的提问来源于stack exchange,提问作者user1331734

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:26:49