The Collings Zone

The home of Adam & Linda Collings

Welcome to Adam and Linda's place. We are a Christian couple from Tasmania. We have two adorable children. Here you will find some of our writings, and a little other material. Make yourself at home.

Home   |   About Us   |   Adam's Writing   |   Software Projects   |   The Blog

Search the Bible with BibleGateway.com
  
  
  
BibleGateway.com is a service of Gospelcom.net

Monday, August 31, 2009

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

System.Runtime.InteropServices.Marshal.ReleaseComObject(oFind);
oFind = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSelection);
oSelection = null;

This succesfully resolved the problem for me.

Sources:

Labels:

0 Comments:

Post a Comment

<< Home