C#替换Word文本框中的内容(不使用Bookmark)
主要参考StoryRanges,NextStoryRange,WdStoryType,Range这几个类。
Replace text in Word textbox objects using VSTO and C#
/// <summary> /// 查找并替换文本 /// </summary> /// <param name="wordApp"></param> /// <param name="oldStr"></param> /// <param name="newStr"></param> public void SearchReplace(string oldStr, string newStr) { #region 文字区域 object replaceAll = WdReplace.wdReplaceAll; wordApp.Selection.Find.ClearFormatting(); wordApp.Selection.Find.Text = oldStr; wordApp.Selection.Find.Replacement.ClearFormatting(); wordApp.Selection.Find.Replacement.Text = newStr; wordApp.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); #endregion #region 文本框 StoryRanges sr = wordDoc.StoryRanges; foreach (Range r in sr) { Range r1 = r; if (WdStoryType.wdTextFrameStory == r.StoryType) { do { r1.Find.ClearFormatting(); r1.Find.Text = oldStr; r1.Find.Replacement.ClearFormatting(); r1.Find.Replacement.Text = newStr; r1.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); r1 = r1.NextStoryRange; } while (r1 != null); } } #endregion }