如何检查范围是否在命名范围内?

时间:2014-09-16 05:16:05

标签: google-apps-script google-sheets

我需要检查onEdit函数中编辑的单元格是否是命名范围的一部分。 Excel VBA中的类似内容:

If Not Intersect(Edited Cell, Range("NamedRange")) Is Nothing Then ...

有什么想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

至少相当简陋的东西会给你一些想法:

function _check_rows(range, namedRange) {
  var _result = false,
      _range_row_begin,
      _range_row_end,
      _namedRange_row_begin,
      _namedRange_row_end;
  if (range && namedRange) {
    _range_row_begin = range.getRow(),
    _range_row_end = range.getLastRow(),
    _namedRange_row_begin = namedRange.getRow(),
    _namedRange_row_end = namedRange.getLastRow(),
    _result = _range_row_begin >= _namedRange_row_begin && _range_row_end <= _namedRange_row_end;
  }
  return _result;
}

function _check_columns(range, namedRange) {
  var _result = false,
      _range_column_begin,
      _range_column_end,
      _namedRange_column_begin,
      _namedRange_column_end;
  if (range && namedRange) {
    _range_column_begin = range.getColumn(),
    _range_column_end = range.getLastColumn(),
    _namedRange_column_begin = namedRange.getColumn(),
    _namedRange_column_end = namedRange.getLastColumn(),
    _result = _range_column_begin >= _namedRange_column_begin && _range_column_end <= _namedRange_column_end;
  }
  return _result;
}

function _setNamedRange(name) {
  var _ss = SpreadsheetApp.getActiveSpreadsheet();
  _ss.setNamedRange(name, _ss.getRange('Sheet 1!C3:D6'));
}

function Intersect(range, namedRange) {
  var _result = false,
      _ss,
      _sheet,
      _range,
      _namedRange;
  if (range && namedRange) {
    _ss = SpreadsheetApp.getActiveSpreadsheet(),
    _sheet = _ss.getActiveSheet(),
    _namedRange = _ss.getRangeByName([_sheet.getName(), '!', namedRange].join('')),
    _range = _sheet.getRange(range),
    _result = _check_rows(_range, _namedRange) && _check_columns(_range, _namedRange);
  }
  return _result;
}

function test_Intersect() {
  var _currentCell = 'C4',
      _namedRange = 'NamedRange'; // NamedRange = 'Sheet 1!C3:D6';
  _setNamedRange(_namedRange);
  if (!Intersect(_currentCell, _namedRange))
    Logger.log('TRUE');
  else
    Logger.log('FALSE');
}