71

I'm trying to get the following formula to work:

function setDataValid(range, sourceRange) {
  var rule = SpreadsheetApp.newDataValidation().requireValueInRange(sourceRange, true).build();
  range.setDataValidation(rule);
}

function onEdit() {
  var aCell = SpreadsheetApp.getActiveSheet().getActiveCell();
  var aColumn = aCell.getColumn();

  if (aColumn == 2 && SpreadsheetApp.getActiveSheet().getName() == 'Local' ) {
    var range = SpreadsheetApp.getActiveSheet().getRange(aCell.getRow(), aColumn + 1);
    var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(aCell.getValue());
    setDataValid(range, sourceRange)
  }
}

When debugging onEdit() it shows that sourceRange in setDataValid(range, sourceRange) is null. As the range is in my sheet 'Local' I'm trying to change the getActiveSpreadsheet() to a get spreadsheet by name. Anyone who can help ?

3 Answers 3

152

Use get sheet by name on the spreadsheet:

var sheet = SpreadsheetApp.getActive().getSheetByName('Local')
0
11

Its very simple just get the sheet by name, the syntax is as follows as per the documentation.

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Expenses");
3
  • 1
    getActive and getActiveSpreadsheet are synonymous. Prefer the former as the latter is too similar to getActiveSheet, which does not return a Spreadsheet object.
    – tehhowch
    Mar 14, 2019 at 11:09
  • I dont believe this is true any longer. getActiveSpreadsheet().getSheetByName(xxx) returns an error currently. getActive().getSheetByName() works.
    – crthompson
    Jul 23, 2021 at 15:58
  • Where exactly is getSheetByName documented? It's used in several places in the Sheet Class doc page but never explicitly documented. May 15 at 13:54
1

Please check the statement

var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(aCell.getValue());

This should be the one returning null. For the cause look at the official documentation here.

var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('Local!TaxRates')

should get the range.

3
  • Thanks. But I need the getRangeByName value to depend on the value in the cell I have just edited Feb 20, 2018 at 7:47
  • Use the parameter of the getRangeByName to include both your sheet name and the cell value, which has the named range name. var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('Local!'+aCell.getValue()) Feb 20, 2018 at 8:05
  • Still comes back like this Argument cannot be null: range (line 2, file "Code") Feb 20, 2018 at 8:13

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.