Home > Mobile >  Best practice for filling a text range in Google Docs App Script
Best practice for filling a text range in Google Docs App Script

Time:02-11

I use a template in google docs for a letter and I want to fill the letter after the (dynamic) header of the letter automatically via App Scripts. Is there any best practice to set the text always to the same position? I've tried to use a placeholder and replace it. But sometimes I need to replace the text more than one time. Thank you very much for your hints

CodePudding user response:

I don't know about best practice but you could use bookmarks. You can't name them but if you know, lets say, the 5th bookmark is user name then cycle through the bookmarks and when you get to the 5th edit the text.

Before:

enter image description here

function myFunction() {
  try {
    var doc = DocumentApp.getActiveDocument();
    var bmarks = doc.getBookmarks();
    var position = null;
    var i = 0;
    for( i=0; i<bmarks.length; i   ) {
      console.log(bmarks[i].getId());
      position = bmarks[i].getPosition();
      position.insertText("i = " i)
    }
  }
  catch(err) {
    console.log(err);
  }
}

After:

enter image description here

CodePudding user response:

In your situation, how about using NamedRange? enter image description here

Reference:

  • Related