getRange with named range google spreadsheet using scripts

ε祈祈猫儿з 提交于 2019-11-30 11:43:52

https://developers.google.com/apps-script/class_spreadsheet#getRangeByName

Custom function returning A1 address of named range:

function myGetRangeByName(n) {  // just a wrapper
  return SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n).getA1Notation();
}

Then, in a cell on the spreadsheet:

=myGetRangeByName("Names")

This would put whatever "Names" is defined as into the cell. It will NOT update when you redefine "Names," because of GAS's aggressive caching. You can, however, force GAS to update it on every sheet calculation.

=myGetRangeByName("Names",now())

The javascript will ignore the unused parameter.

The following code does what I think you intend. When the first column of the sheet is edited, it sorts the range based on that column.

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var editedCell = ss.getActiveCell();
  var columnToSortBy = 1;
  var tableRange = ss.getRangeByName("Names");
  if ( editedCell.getColumn() == columnToSortBy ) {
    tableRange.sort(columnToSortBy);
  }
}

This will NOT work if you move the list off column A, because getColumn() returns the absolute column, not the location of the cell in the range. You would have to add code to adjust for that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!