I am trying to write a Google Apps Script for Documents that will insert some text, and then add inserted text to a named ranged. To make sure that the inserted text is saved to a named range, I just want to select the inserted text.
Here's the code:
function insertText() {
var doc = DocumentApp.getActiveDocument();
var docUi = DocumentApp.getUi();
var cursor = doc.getCursor();
if (cursor) {
var insert = cursor.insertText('{insertedtext}');
var rangeBuilder = doc.newRange();
if (insert) {
rangeBuilder.addElement(insert);
} else {
docUi.alert('Cannot insert text here.');
}
} else {
docUi.alert('Cannot find a cursor.');
}
var savedInsert = rangeBuilder.build()
doc.addNamedRange('myInsertedText', savedInsert)
doc.setSelection(doc.getNamedRangeById('myInsertedText').getRange());
}
When I run the script, doc.setSelection(doc.getNamedRangeById('myInsertedText').getRange());
generates the following error:
TypeError: Cannot call method "getRange" of null.
Any idea of what I am doing wrong?
'myInsertedText'
is actually the namedRange's name, not the id:
var namedRange = doc.addNamedRange('myInsertedText', savedInsert);
var namedRangeId = namedRange.getId();
doc.setSelection(doc.getNamedRangeById(namedRangeId).getRange());