简体   繁体   中英

Apps Script - Google Docs - RangeBuilder

When I run this code while selecting a table element on my document, I get the following error:

  • Exception: The parameters (DocumentApp.RangeElement) don't match the method signature for DocumentApp.RangeBuilder.addElement.

The source of the issue lies in my function nameRange(doc, el, name):

  • rangeBuilder.addElement(el)

I don't understand how I'm receiving this error, given that the parameter for.addElement is an element; this code returns a table element just prior to assigning it to a namedRange.

If you could please help me spot the error in my code, and maybe a solution to this issue, I would greatly appreciate it.

function main() {
  const doc = DocumentApp.getActiveDocument()
  let selection = doc.getSelection().getRangeElements()
  let toRename = [];

  // looping through selection to get desired table element
  for (let i = 1; i < selection.length - 1; i++) {
    let element = selection[i]
    let type = element.getElement().getType()
    toRename.push(selection[i])
  }
  
  // naming the selection with the custom fuction nameRange()
  for (const item of toRename) {
    nameRange(doc, item, "Range Title")
  }
}

/**
 * Names the given range into an accessible Named Range
 * @type {RangeElement} RangeElement
 * @param {DocumentApp.Document} doc - The Document selected.
 * @param {RangeElement} el - The element object to give the Named Range to.
 * @param {string} name - The name to give the Named Range.
 * @returns void
 */
function nameRange(doc, el, name) {
  let rangeBuilder = doc.newRange()
  rangeBuilder.addElement(el)
  doc.addNamedRange(name, rangeBuilder.build())
}

First of all your script will not work if selection.length is 1. The loop will not execute. Secondly you are passing a RangeElement to nameRange not an Element.

Change

rangeBuilder.addElement(el)

To

rangeBuilder.addElement(el.getElement()) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM