Stack Overflow with Word Automation Replace – SOLVED

When performing Word automation, Word will sometimes throw a System.StackOverflowException, which you cannot catch, while performing a find/replace operation. It is usually the Find.Replacement.ClearFormatting(); call that leads to this exception.

The solution to this is simple, use late binding. In fact, it is recommended that you use late binding whenever performing office automation.

The resulting code would be something like

object Selection = oWord.Selection;
object myFind = oWord.Selection.Find;
object Optional = Type.Missing;
object wd = Word.WdReplace.wdReplaceAll;
object[] Parameters;
object findText = “Findtext”;
object replaceText = “Replacetext”;

Parameters = new object[15];
Parameters[0] = findText;
Parameters[1] = Optional;
Parameters[2] = Optional;
Parameters[3] = Optional;
Parameters[4] = Optional;
Parameters[5] = Optional;
Parameters[6] = Optional;
Parameters[7] = Optional;
Parameters[8] = Optional;
Parameters[9] = replaceText;
Parameters[10] = wd;
Parameters[11] = Optional;
Parameters[12] = Optional;
Parameters[13] = Optional;
Parameters[14] = Optional;

myFind.GetType().InvokeMember(“Execute”, BindingFlags.InvokeMethod, null, myFind, Parameters);

Don’t forget to free the objects you have used

oFind = null;
oSelection = null;

This succesfully resolved the problem for me.



About Adam David Collings

Adam Collings is a writer of speculative fiction who works as a software engineer during the day. He lives in Tasmania, Australia with his wife and two children. Adam is currently working on a science fiction novel.
This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s