Word Automation : Replace do not work after TypeText
- by wishper
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 "" 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 (Thanks Microsofts 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 values 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);
}