I am trying to build an add-in on which I will have some input fields and the values of those input fields will be added to a MS word template on a button action.
The template looks like:
Lorem ipsum dolor sit amet, consectetur adipiscing #value_no_1# elit. Integer placerat leo eget tortor malesuada, eu ultrices mauris #value_no_2# rutrum. Vestibulum vel mattis tellus #valuen_no_3#.
Vivamus sit amet ante sit amet lacus #valuen_no_4# ullamcorper placerat.
Donec pretium tincidunt orci, eget vestibulum eros #value_no_5# sollicitudin quis.
Morbi euismod sed eros nec ultrices. Vestibulum nec ipsum at ipsum dictum sagittis et vel felis #valuen_no_6#.
Aenean a varius erat.
Vestibulum euismod eget lectus eu #value_no_7# scelerisque.
Etiam vel bibendum est. Sed venenatis tortor non ex tempor hendrerit #value_no_8#. Cras auctor leo malesuada tortor tempor, at pharetra orci sollicitudin #value_no_9#.
The function for replacing the text is the following:
function fillIn() {
Word.run(function (context) {
// Queue a command to search the document with a wildcard
// for any string of characters that starts with 'to' and ends with 'n'.
var searchResults = context.document.body.search("#*#", { matchWildcards: true });
// Queue a command to load the search results and get the font property values.
context.load(searchResults, "text");
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log("Found count: " + searchResults.items.length);
// Queue a set of commands to change the font for each found item.
for (var i = 0; i < searchResults.items.length; i++) {
console.log(searchResults.items[i].text);
searchResults.items[i].insertText("Hello", "Replace");
return context.sync();
}
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync();
});
}).catch(function (error) {
console.log("Error: " + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}
For the first 3 or 4 values the text is replaced correctly, so instead #value_no_1# I will get hello, but at latter values as #value_no_8# I will get something hello_no_8#. I guess this happens because the number of characters inside the ranges is changing because of new value entered.
Another remark would be that : searchResults.items[i].text returns the correct value #value_no_8#.
But when calling the replaceText I get hello_no_8# instead of hello.
I have researched the docs and don't have any good example on how to approach bulk writing in the doc.
Has someone an idea on how to fix this or another idea on how I can approach the bulk replacing of text?