次のコードを使用して、Word 文書を開き、検索対象のテキストを強調表示できます。
private void btnFind_Click(object sender, EventArgs e)
{
object fileName = "xxxxx"; //The filepath goes here
string textToFind = "xxxxx"; //The text to find goes here
Word.Application word = new Word.Application();
Word.Document doc = new Word.Document();
object missing = System.Type.Missing;
try
{
doc = word.Documents.Open(ref fileName, 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, ref missing);
doc.Activate();
foreach (Word.Range docRange in doc.Words)
{
if(docRange.Text.Trim().Equals(textToFind,
StringComparison.CurrentCultureIgnoreCase))
{
docRange.HighlightColorIndex =
Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
docRange.Font.ColorIndex =
Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
次のステートメントを使用して、Microsoft.Office.Interop.Word への参照を追加する必要があります。
using Word = Microsoft.Office.Interop.Word;
関数としてやりたい場合は、それを変更します