Click here to Skip to main content
15,943,089 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I wrote the following code to find the location of a text string in a word document. It works but it is glacially slow. How do I speed it up?
public int find_text(string some_text)
{
    int point0;
    int location;
    int text_length;
    string curr_text;
    bool found;
    location = -1;
    text_length = some_text.Length;
    point0 = -1;
    found = false;
    while (point0 < pEnd - text_length && !found)
    {
        point0++;
        curr_text = pDoc.Range(point0, point0 + text_length).Text;
        if (curr_text == some_text)
        {
            location = point0;
            found = true;
        }
    }
    return location;
}


What I have tried:

I've tried to use the Range.Find interface class. It tells me if the text was found but I cannot find its location.
Posted
Updated 6-Feb-20 5:10am
Comments
Maciej Los 5-Feb-20 16:42pm    
Would you like to replace text or change its formatting?

 
Share this answer
 
Comments
Fred Andres 6-Feb-20 11:11am    
Thanks for the help Maciej. Note my solution below based on your information.
Maciej Los 6-Feb-20 12:00pm    
You're very welcome.
Cheers!
Maciej
Thanks for your help Maciej. With your information I was able to come up with the following solution which is lightening fast:
public void find_and_replace_text(string curr_text, string new_text)
{
    Word.Find findObject;
    var missing = Type.Missing;
    findObject = pDoc.Content.Find;
    findObject.ClearFormatting();
    findObject.Text = curr_text;
    findObject.Replacement.ClearFormatting();
    findObject.Replacement.Text = new_text;
    object replaceAll;
    replaceAll = Word.WdReplace.wdReplaceAll;
    findObject.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);
}
 
Share this answer
 
Comments
Maciej Los 6-Feb-20 12:01pm    
5ed!
You can accept your answer as a solution too.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900