Home > Software design >  Google AppsScript: can't get the function to work on all cells
Google AppsScript: can't get the function to work on all cells

Time:12-21

I've written a function that throws a message (toast) every time you put a value that is not a number in the cell. It works with one cell. Problem is, I want it to work in several cell ranges but it only works on the first cell of the range. This is the code:

function onEdit() {
    var app = SpreadsheetApp;
    var activeSheet = app.getActiveSpreadsheet().getSheetByName("TEST")
    var workingCell = activeSheet.getRange("B13:B27").getValue();

    if (typeof workingCell != "number" && workingCell != "") {
        SpreadsheetApp.getActive().toast("This is not a number, please try again.");
    }
}

As you can see, in the 'gerRange()' part, I'm defining that I want the code to work in the range B13 to B27, however it only works on the first cell (B13).

Can anyone tell me what could be done to make it work on a range?

Thank you.

CodePudding user response:

I believe your goal is as follows.

  • You want to run the script of SpreadsheetApp.getActive().toast("This is not a number, please try again.") when the cells of "B13:B27" on "TEST" sheet are edited.

In this case, how about the following modified script?

Modified script:

function onEdit(e) {
  var { range } = e;
  var workingCell = range.getValue();
  if (
    range.getSheet().getSheetName() == "TEST" &&
    range.columnStart == 2 &&
    range.rowStart >= 13 &&
    range.rowEnd <= 27 &&
    typeof workingCell != "number" &&
    workingCell != ""
  ) {
    SpreadsheetApp.getActive().toast("This is not a number, please try again.");
  }
}

Note:

  • In this modification, the event object is used. So when you use this script, please edit the cells of "B13:B27" on "TEST" sheet. By this, the script is run.
  • When you directly run this script with the script editor, an error like Cannot destructure property 'range' of 'e' as it is undefined. occurs. Please be careful about this.

Reference:

  • Related