I’m working with Google Apps Script and trying to create named ranges from selected table elements in a Google Document. However, I keep running into an error that I can’t figure out.
When I select a table in my document and run my script, I get this error message:
- Exception: The parameters (DocumentApp.RangeElement) don’t match the method signature for DocumentApp.RangeBuilder.addElement.
The problem seems to be happening in my custom function createNamedRange(document, element, rangeName) specifically at this line:
- builder.addElement(element)
I’m confused because the documentation says addElement should accept an element parameter, and my code is definitely passing a table element to it. The element exists and is valid right before I try to add it to the range builder.
Can someone help me understand what’s going wrong here? Any suggestions for fixing this would be really helpful.
function initialize() {
const document = DocumentApp.getActiveDocument()
let selectedRange = document.getSelection().getRangeElements()
let elementsToProcess = [];
// iterate through selected elements to find tables
for (let index = 1; index < selectedRange.length - 1; index++) {
let currentElement = selectedRange[index]
let elementType = currentElement.getElement().getType()
elementsToProcess.push(selectedRange[index])
}
// create named ranges using helper function
for (const element of elementsToProcess) {
createNamedRange(document, element, "My Range Name")
}
}
/**
* Creates a named range from the specified element
* @param {DocumentApp.Document} document - The active document
* @param {RangeElement} element - The element to convert to named range
* @param {string} rangeName - Name for the new range
*/
function createNamedRange(document, element, rangeName) {
let builder = document.newRange()
builder.addElement(element)
document.addNamedRange(rangeName, builder.build())
}