Export (0) Print
Expand All
Expand Minimize
3 out of 6 rated this helpful - Rate this topic

How to: Loop Through Found Items in Documents

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.

The Find object has a Found property, which returns True whenever a searched-for item is found. You can loop through all instances found in a Range using the Execute method. You can make use of this in your code, as shown in the following example.

To loop through found items

  1. Declare a Range object.

    Word.Range rng = this.Content; 
    
    
  2. Use the Found property in a loop to search for all occurrences of the string in the document, and increment an integer variable by 1 each time the string is found.

    rng.Find.ClearFormatting(); 
    rng.Find.Forward = true; 
    rng.Find.Text = "find me"; 
    
    rng.Find.Execute(
        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);
    
    while (rng.Find.Found) 
    { 
        intFound++;
        rng.Find.Execute(
            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);
    } 
    
    
  3. Display the number of times the string was found in a MessageBox.

    MessageBox.Show("Strings found: " + intFound.ToString()); 
    
    

The following example shows the complete method.

Example

private void FindLoop() 
{ 
    int intFound = 0; 
    Word.Range rng = this.Content; 

    rng.Find.ClearFormatting(); 
    rng.Find.Forward = true; 
    rng.Find.Text = "find me"; 

    rng.Find.Execute(
        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);

    while (rng.Find.Found) 
    { 
        intFound++;
        rng.Find.Execute(
            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);
    } 

    MessageBox.Show("Strings found: " + intFound.ToString()); 
}

See Also

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.