google-sheetsgoogle-apps-scripttriggers

onEdit to run only on one cell in one sheet


I'm new and playing around with Google Sheet Apps Script.

I'm trying to sheet on onEdit trigger for only one cell (B5). It contains a dropdown list. When staff selects the month (eg. May), it runs the May() script.

The below code works. But when I add an if() it suddenly stops.

function onEdit(e) {
  let ss = SpreadsheetApp;
  let activeSheet = ss.getActive().getActiveSheet();
  let dropDownCell = activeSheet.getRange('B5').getValue();
  if (dropDownCell == 'January'){ return Jan() };
  if (dropDownCell == 'February'){ return Feb() }
  if (dropDownCell == 'March'){ return Mar() };
  if (dropDownCell == 'April'){ return Apr() };
  if (dropDownCell == 'May'){ return May() };
  if (dropDownCell == 'June'){ return Jun() };
  if (dropDownCell == 'July'){ return Jul() };
  if (dropDownCell == 'August'){ return Aug() };
  if (dropDownCell == 'September'){ return Sep() };
  if (dropDownCell == 'October'){ return Oct() }
  if (dropDownCell == 'November'){ return Nov() };
  if (dropDownCell == 'December'){ return Dec() };
  }

Solution

  • I believe your goal is as follows.

    In this case, how about the following modification? In this modification, the event object e is used.

    From:

    function onEdit(e) {
      let ss = SpreadsheetApp;
    

    To:

    function onEdit(e) {
      const { range } = e;
      const sheet = range.getSheet();
      if (range.getA1Notation() != "B5") return;
      let ss = SpreadsheetApp;
    

    Or, if you want to also check the sheet name, you can also the following modification.

    function onEdit(e) {
      const sheetName = "Sheet1"; // Please set the sheet name.
      const { range, value } = e;
      const sheet = range.getSheet();
      if (range.getA1Notation() != "B5" || sheet.getSheetName() != sheetName) return;
      let ss = SpreadsheetApp;
    

    Note:

    References: