Reputation: 1519
The Office JS has provided the following function in preview, but I couldn't find any example.
Here is what I tried but it doesn't seem to work, any idea what I am missing here, since this code inserts the text but the bookmark is not created.
Word.run(function (context)
{
let range = context.document.getSelection();
return context.sync().then(function ()
{
range.insertText(`Test Bookmark`, Word.InsertLocation.replace);
let uniqueStr = new Date().getTime();
let bookmarkName = `Test_BookmarkCode_${uniqueStr}`;
range.insertBookmark(bookmarkName);
});
});
Cross posted here.
Upvotes: 8
Views: 1489
Reputation: 41
(Cannot comment, pls excuse my posting this as an answer.) Two things that got in my way when I implemented something similar to the above solution:
If you violate either rule you'll get an InvalidArgument exception. I only tried this with the Windows Desktop version of Word 2019, but this behavior is probably the same with other versions.
Upvotes: 0
Reputation: 1519
So, here is the working code. Apparently, when we insertText, a new range is returned, we need to use that range to insertBookmark.
Word.run(function (context)
{
let range = context.document.getSelection();
return context.sync().then(function ()
{
let insertedTextRange = range.insertText(`Test Bookmark`, Word.InsertLocation.replace);
let uniqueStr = new Date().getTime();
let bookmarkName = `Test_BookmarkCode_${uniqueStr}`;
insertedTextRange.insertBookmark(bookmarkName);
});
});
Upvotes: 3