When you use a Selection object to find text, any search criteria you specify are applied only against currently selected text. If the Selection is an insertion point, then the document is searched. When the item is found that matches the search criteria, it is automatically selected.
It is important to note that the Find criteria are cumulative, which means that criteria are added to previous search criteria. Clear formatting from previous searches by using the ClearFormatting method prior to the search.
To find text using a Selection object
Assign a search string to a variable.
Dim findText As String = "find me"
object findText = "find me";
Clear formatting from previous searches.
Application.Selection.Find.ClearFormatting()
Application.Selection.Find.ClearFormatting();
Execute the search and display a message box with the results.
If Application.Selection.Find.Execute(findText) = True Then
MessageBox.Show("Text found.")
Else
MessageBox.Show("The text could not be located.")
End If
if (Application.Selection.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("The text could not be located.");
}
The following example shows the complete method.
Private Sub SelectionFind()
Dim findText As String = "find me"
Application.Selection.Find.ClearFormatting()
If Application.Selection.Find.Execute(findText) = True Then
MessageBox.Show("Text found.")
Else
MessageBox.Show("The text could not be located.")
End If
End Sub
private void SelectionFind()
{
object findText = "find me";
Application.Selection.Find.ClearFormatting();
if (Application.Selection.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("The text could not be located.");
}
}