替换书签内容而不删除书签

Replace bookmarks content without removing the bookmark

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

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

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

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

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

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);
    }
}

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

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();
    }
}

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

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

innerBookmark.Range.Text = newText;

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

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