Reputation: 43
Apologies - new to Javascript and Office.js But it's time to convert my .NET formatting ribbons over to be cross platform. A bit of a learning curve.
I use this function that I found the Addin tutorial, to successfully apply a paragraph style, but I've tried tweaking it (see below) and they while I have learned that it's important to completely shut down the addin, exit out of word and go back in and reload before testing changes (very tedious), it still applies to character style to the entire paragraph. Grr
function applyemphasisstyle() {
Word.run(function (context) {
var pars = context.document.getSelection().paragraphs;
pars.load();
return context.sync().then(function () {
for (var i = 0; i < pars.items.length; i++) {
pars.items[i].style = "Emphasis";
}
return context.sync();
})
}) //needed for Stack overflow
.catch(function (error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}
I've tried changing:
var pars = context.document.getSelection().paragraphs;
to
var pars = context.document.getSelection().getTextRanges;
I've tried just removing ".paragraphs"
I've tried changing ".paragraphs" to ".words" etc
same result - applies the style, but the entire paragraph, not the selected word.
Thanks for any help you can provide!
Upvotes: 2
Views: 435
Reputation: 9784
This code works for me. Since you are selecting a single word, there's nothing to loop through and since you are writing to the style property, instead of reading it, there's no need to load the text object.
return Word.run(function(context) {
var selectedText = context.document.getSelection();
return context.sync()
.then(function () {
selectedText.style = "Emphasis";
})
});
I recommend that you use the Script Lab tool to work out the logic of your script.
Upvotes: 1