Replace does not work after TypeText

529 Views Asked by At

I need to generate doc (real doc, not docx) files, the "best" way I have found is to use word automation (Word 2010). I have files that I open, and then replace values inside before saving it on a new name. (Ex: I replace "CHRONO" with "155023"). To do this, I use the Application.Selection.Find. I just had a problem when the new value had more than 255 characters (Microsoft's limitations ...). To avoid this problem, I use TypeText in this case. My problem now is once I use TypeText, the Replace do not work anymore. And I can't find why. Any idea will be greatly appreciated.

My code is in a function, called in a foreach with each value to replace:

private void Replace(Application app, string name, string newValue)
{
    Selection selection = app.Selection;
    Find find = selection.Find;
    Replacement replacement = find.Replacement;

    find.ClearFormatting();
    find.Text = "<" + name + ">";

    // Word limitation : can't replace with more than 255 characters, 
    // use another way to do it if that's the case
    if (tempNewValue.Length < 255)
    {
        replacement.ClearFormatting();
        replacement.Text = tempNewValue;
        find.Execute(Replace: replaceAll);
    }
    else
    {
        while (find.Execute())
        {
            selection.TypeText(tempNewValue);
        }
    }

    Marshal.ReleaseComObject(replacement);
    Marshal.ReleaseComObject(find);
    Marshal.ReleaseComObject(selection);
}
1

There are 1 best solutions below

0
On

I found the problem. While running the program in debug with word visible, I saw exactly what it does and why it did not work.

In fact, the Replace() worked, but it replace only the occurrences that are after the cursor. To counter this, I need to reset the cursor to the origin of the document :

else
{
    while (find.Execute())
    {
        selection.TypeText(tempNewValue);
    }
    selection.GoTo(1, 1);
}