下面的代码在Word文档中查找单词“家庭”的实例。它选择并删除实例。该代码工作正常,但我想查找仅突出显示单词的所有实例。
public void FindHighlightedText()
{
const string filePath = "D:\\COM16_Duke Energy.doc";
var word = new Microsoft.Office.Interop.Word.Application {Visible = true};
var doc = word.Documents.Open(filePath);
var range = doc.Range();
range.Find.ClearFormatting();
range.Find.Text = "Family";
while (range.Find.Execute())
{
range.Select();
range.Delete();
}
doc.Close();
word.Quit(true, Type.Missing, Type.Missing);
}
Run Code Online (Sandbox Code Playgroud)
将Find.Highlight属性设置为true。
Interop 使用与 VBA 宏可用的相同对象和方法。您可以通过使用这些步骤记录宏并检查它来找到执行任务所需的操作和属性。
通常,但并非总是,属性与 UI 相匹配。如果某些内容是常规“查找”框中的属性,那么它也可能是界面中的属性Find。
例如,仅搜索突出显示的单词会生成以下宏:
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Run Code Online (Sandbox Code Playgroud)
可以翻译为:
range.Find.ClearFormatting();
range.Find.Highlight=1;
...
while(range.Find.Execute())
{
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
283 次 |
| 最近记录: |