2015/08/26

使用 C# 操作 Word 檔案取代字串,字串太長該怎麼辦

解決方式如下
           object replaceAll = Word.WdReplace.wdReplaceAll;
           object missing = System.Reflection.Missing.Value;
           app.Application.Selection.Find.ClearFormatting();
           app.Application.Selection.Find.Text = (string)findMe;
           app.Application.Selection.Find.Replacement.ClearFormatting();

            if (replaceMe.ToString().Length < 250) //字串若超過 250 時會發生 Exception
           {
                      app.Application.Selection.Find.Replacement.Text = (string)replaceMe;
                      app.Application.Selection.Find.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);
          }
          else  //使用找到後,換字串的方式
         {
                      app.Application.Selection.Find.Execute(
                            ref findMe, ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing, ref missing);
                      app.Application.Selection.Text = (string)replaceMe;
          }