【问题标题】:Replace bookmarks content without removing the bookmark替换书签内容而不删除书签
【发布时间】:2019-06-01 03:22:01
【问题描述】:

我想在不丢失书签的情况下替换书签的文本内容。

foreach(Bookmark b in document.Bookmarks)
{
    b.Range.Text = "newtext";  // text is set in document but bookmark is gone
}

我尝试在文本设置之前设置书签的新范围,但我仍然遇到同样的问题。

我还尝试使用document.Bookmarks.Add(name, range); 重新添加书签,但无法创建范围实例。

【问题讨论】:

    标签: c# api ms-word office-interop


    【解决方案1】:

    我必须阅读书签并临时保存范围。我还必须添加一个已处理项目的列表来避免死循环。

    List<string> bookmarksProcessed = new List<string>();
    
    foreach (Bookmark b in document.Bookmarks)
    {
        if (!bookmarksProcessed.Contains(b.Name))
        {
            string text = getTextFromBookmarkName(b.Name);
            var newend = b.Range.Start + text.Length;
            var name = b.Name;
            Range rng = b.Range;
            b.Range.Text = text;
            rng.End = newend;
            document.Bookmarks.Add(name, rng);
            bookmarksProcessed.Add(name);
        }
    }
    

    【讨论】:

      【解决方案2】:

      看起来你解决了你的问题,但这里有一个更简洁的方法:

      using Office = Microsoft.Office.Core;
      using Microsoft.Office.Tools.Word;
      using System.Text.RegularExpressions;
      using Word = Microsoft.Office.Interop.Word;
      
      //declare and get the current document 
      Document extendedDocument = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveDocument);
      
      List<string> bookmarksProcessed = new List<string>();  
      
      foreach(Word.Bookmark oldBookmark in extendedDocument.Bookmarks)
      {
          if(bookmarksProcessed.Contains(oldBookmark.Name))
          {
              string newText = getTextFromBookmarkName(oldBookmark.Name)
      
              Word.Range newRange = oldBookmark.Range;
      
              newRange.End = newText.Length;
      
              Word.Bookmark newBookmark = extendedDocument.Controls.AddBookmark(newRange, oldBookmark.Name);
      
              newBookmark.Text = newText;
      
              oldBookmark.Delete();
          }
      }
      

      代码未经测试,但应该可以工作。

      【讨论】:

        【解决方案3】:

        使用上述方法,在重新添加之前您仍然会丢失书签。如果您确实需要保留书签,我发现您可以创建一个环绕文本的内部书签(书签中的书签)。拥有内部书签后,您只需要做:

        innerBookmark.Range.Text = newText;
        

        文本替换后,内书签消失,外书签保留。无需设置range.End

        您可以根据自己的情况手动或以编程方式创建内部书签。

        【讨论】:

          猜你喜欢
          • 2015-07-13
          • 1970-01-01
          • 2016-03-24
          • 2015-10-19
          • 1970-01-01
          • 1970-01-01
          • 2012-03-10
          • 2012-04-08
          • 1970-01-01
          相关资源
          最近更新 更多