ArnNun
ArnNun

Reputation: 3

Office.js How to insert 2 content controls, one at start of selection and one at end of selection

In word 2016, when a user selects some text they have an option to place a starting and ending content control at the start and end of a selection. Is there any good way to do this? Whenever I try to insert a content control, it replaces the selected text.

this is what i have:

const ContentControlRange = context.document.getSelection();
const myContentControl = ContentControlRange.insertContentControl();

//set content control properties here

return context.sync().then(function () {
    console.log("creating cc context.sync()");

    //do other stuff
});

and if i call this function twice the last content control just replaces the first content control. Any help appreciated thanks.

I tried:

const ContentControlRange = context.document.getSelection().getRange('After');

but i keep getting an 'Invalid Argument' error.

Upvotes: 0

Views: 722

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25693

The following Script Lab code snippet works for me. It uses three Ranges, although theoretically two would be sufficient. In any case, the original Range (the selection) needs to be retained so that it's possible to first get the position before the selection, then the position after the selection.

This code uses "Start" and "End" as position parameters. If these are not used the content control(s) will replace the selection, same as if you select text then type.

async function
    insertTwoCC() {
    await Word.run(async(context) => {

        let currSel = context.document.getSelection();
        let rngBefore = currSel.getRange("Start");
        let rngAfter = currSel.getRange("End");
        let ccBefore = rngBefore.insertContentControl();
        let ccAfter = rngAfter.insertContentControl();
        await context.sync();
        })
    }

Upvotes: 2

Related Questions