Export (0) Print
Expand All
Expand Minimize

How to: Restore Selections After Searches

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

If you find and replace text in a document, you might want to restore the user's original selection after the search is completed.

The code in the sample procedure makes use of two Range objects. One stores the current Selection, and one sets the entire document to use as a search range.

To restore the user's original selection after a search

  1. Create the Range objects for the document and the current selection.

    Word.Range start = Application.Selection.Range; 
    Word.Range searchArea = Application.ActiveDocument.Range(ref missing, ref missing); 
    
    
  2. Perform the search and replace operation.

    searchArea.Find.ClearFormatting(); 
    searchArea.Find.Text = "find me"; 
    
    searchArea.Find.Replacement.ClearFormatting(); 
    searchArea.Find.Replacement.Text = "Found"; 
    
    object replaceAll = Word.WdReplace.wdReplaceAll; 
    
    searchArea.Find.Execute(
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref replaceAll, ref missing, ref missing, ref missing, ref missing);
    
    
  3. Select the start range to restore the user's original selection.

    start.Select(); 
    
    

The following example shows the complete method.

Example

internal void ReplaceRestoreSelection() 
{ 
    Word.Range start = Application.Selection.Range; 
    Word.Range searchArea = Application.ActiveDocument.Range(ref missing, ref missing); 

    searchArea.Find.ClearFormatting(); 
    searchArea.Find.Text = "find me"; 

    searchArea.Find.Replacement.ClearFormatting(); 
    searchArea.Find.Replacement.Text = "Found"; 

    object replaceAll = Word.WdReplace.wdReplaceAll; 

    searchArea.Find.Execute(
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref replaceAll, ref missing, ref missing, ref missing, ref missing);

    start.Select(); 
}

See Also

Community Additions

ADD
Show:
© 2014 Microsoft