我在word文档中创建了书签。但是,在主要文本部分不在页眉和页脚部分。现在,我想在Primary Header Section中创建书签。
实际上,我正在尝试在运行时更新书签文本。但是,每当我更改书签的文本时,它都会被删除。所以,我必须以编程方式再次创建它。
这是我替换word文档书签文本的代码。
if (doc.Bookmarks.Exists(_bookMarkName))
{
object oBookMark = _bookMarkName;
//Getting Bookmark Object
Microsoft.Office.Interop.Word.Bookmark bookmark = doc.Bookmarks.get_Item(ref oBookMark);
//calculating range to create bookmark.
object start = bookmark.Range.Start;
object end = bookmark.Range.Start + _value.Length;
//After replacing this text, bookmark will be removed from the document. So, we have to creat it again.
bookmark.Range.Text = _value;
//Creating range from new values.
object range = doc.Range(ref start, ref end);
doc.Bookmarks.Add(_bookMarkName, ref range); //Adding new bookmark with new range
}
因此,此代码中的问题是StoryType
对象的bookmark
属性在替换书签文本之前将为Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory
。但是,在创建新书签后,属性StoryType
将被视为Microsoft.Office.Interop.Word.WdStoryType.wdMainTextStory
而不是Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory
。那么,如何在创建书签时更改该属性或指定该属性。属性StoryType
为ReadOnly
。所以,创建书签后我无法分配它。
`
答案 0 :(得分:0)
问题基本上是以doc为起点创建新范围。如果Range对象没有Range方法,我认为您必须从书签的范围中获取相关的StoryRange,然后使用GetRange获取相应故事中的范围。我没有检查......
...因为这不应该是必要的,假设您希望替换书签“覆盖”您刚刚插入的文本,因为您应该可以执行更多这样的操作,假设您可以重新转换此VBA语法回到C#
Dim bm As Word.Bookmark
Dim bookMarkName As String
Dim doc As Word.Document
Dim newValue As String
Dim rng As Word.Range
'.
'.
If doc.Bookmarks.Exists(bookMarkName) Then
' Could do the following two statements in one
Set bm = doc.Bookmarks(bookMarkName)
Set rng = bm.Range
rng.Text = newValue
doc.Bookmarks.Add bookMarkName, rng
Set rng = Nothing
Set bm = Nothing
End If