在整个word文档中搜索一个单词而不打开它

本文关键字:单词 一个 word 文档 搜索 | 更新日期: 2023-09-27 18:08:09

我想在整个word文档中搜索一个单词,而不打开它。

我在每个网站搜索并阅读这里的所有问题,但使用此代码(使用Range Object)时出现错误

object findText = "find me";
Word.Range rng = this.Paragraphs[2].Range; 
rng.Find.ClearFormatting();
if (rng.Find.Execute(ref findText,
    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
    ref missing, ref missing)) 
{ 
    MessageBox.Show("Text found.");
} 
else 
{ 
    MessageBox.Show("Text not found.");
} 
rng.Select(); 

但是我有一个错误在

Paragraphs[2]

打开大文件时。错误是:

ref失踪

在整个word文档中搜索一个单词而不打开它

您应该使用

计算整个文档中的段落数
int docc = wordfile.Paragraphs.Count;

所以当你打开大文件时,它会计算文件中的所有段落。然后在范围代码

中使用((docc))
Range rng = wordfile.Paragraphs[docc].Range;

第二个错误可以使用((Type)。(ref Missing))代替((ref Missing))

所以代码是

object findText = "find me";
int docc = wordfile.Paragraphs.Count;
Range rng = wordfile.Paragraphs[docc].Range;
rng.Find.ClearFormatting();
if (rng.Find.Execute(ref findText,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
Type.Missing, Type.Missing)) 
 { 
  MessageBox.Show("Text found.");
 } 
else 
{ 
 MessageBox.Show("Text not found.");
} 
rng.Select();