js 动态添加Word书签

  添加书签的基本原理是光标定位到要添加书签的位置,获取选择的域,将获取到的域添加到书签集合中。接下来是Js代码示例:
  首先获取文档的ActiveDcoument对象,我这里获取ActiveDcoument对象使用的是封装的NTKO对象方法docEditor._getDocument()。

  先定位光标位置,我这里是根据上一个书签来动态定位下个书签的位置:

// 获取指定名称的书签对象
var markRange = docEditor._getDocument().BookMarks(bookMark);
// 设置文档的选择域
markRange.Select();

//将光标位置换行
var oldEnd = docEditor._getDocument().Application.Selection.End;
docEditor._getDocument().Application.Selection.Start = oldEnd;
docEditor._getDocument().Application.Selection.End = oldEnd;
docEditor._getDocument().Application.Selection.Text = "\r\n";   

// 跳到选择域的尾部,在尾部重新获取选择域
//此时获取到的域是新行首位
var oldEnd = docEditor._getDocument().Application.Selection.End;
docEditor._getDocument().Application.Selection.Start = oldEnd;
docEditor._getDocument().Application.Selection.End = oldEnd;
// 获取新的选择域对象,并在域中插入内容
var range = docEditor._getDocument().Application.Selection.Range;
range.Text = addText;
// 将新的选择域添加到书签集合中
docEditor._getDocument().Bookmarks.Add(bookmarkName, range);

  下面是VBA宏代码示例,可以在word的宏编辑器中直接执行:

Sub test1()
     ’ 定位到当前选择域的尾部
     Selection.EndKey
     ’ 生成一个新的选择域并在域中添加回车换行及空格
     iStart = ActiveDocument.ActiveWindow.Selection.End
     ActiveDocument.ActiveWindow.Selection.Start = iStart
     ActiveDocument.ActiveWindow.Selection.End = iStart
     ActiveDocument.ActiveWindow.Selection.Text = Chr(13) & Chr(10) & "                            "
     ’ 在上一个域的后面再次获取新的域
     iStart = ActiveDocument.ActiveWindow.Selection.End
     ActiveDocument.ActiveWindow.Selection.Start = iStart
     ActiveDocument.ActiveWindow.Selection.End = iStart
     ’ 在新的域中添加四个空格做占位符
     ActiveDocument.ActiveWindow.Selection.Text = " "
     ’ 将当前的域添加到书签集合中
     ActiveDocument.Bookmarks.Add Name:="hgyj11", Range:=ActiveDocument.ActiveWindow.Selection.Range

End Sub

你可能感兴趣的:(js 动态添加Word书签)