Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

385
Visualizações
Replace text in MS Word Add-in JS API

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try this:

Word.run(async (context) => {
  var body = context.document.body;
  var options = Word.SearchOptions.newObject(context);
  options.matchCase = false
  var searchResults = context.document.body.search("Hello Finder", options);
  context.load(searchResults, 'text, font');

  return context.sync().then(() => {
    var results = 'Found count: ' + searchResults.items.length + '; we highlighted the results.';

    for (var i = 0; i < searchResults.items.length; i++) {
      searchResults.items[i].insertText("Hello Replaced", "Replace");
    }


    return context.sync().then(function () {
      console.log(results);
    });
  });
})
  .catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
      console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
  });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda