for-loopgoogle-apps-scriptgoogle-sheets

Clarification on using the forEach() function


Note: The purpose of this was just to try and learn how the forEach function works so that I can try to apply it elsewhere.

I'm trying to learn how to use the forEach function on apps script, but it doesn't work when I try to use it. I want to loop through the first 15 cells of column A and set the background to red.

I tried this but when I run it, it says "cell out of range"

 function onOpen() {
 
  var range = SpreadsheetApp.getActive().getRange("A1:A15");
  var values = range.getValues();
  values.forEach(function(row) {
    range.getCell(row,1).setBackground('red');
   
 });
 }

Solution

  • Modification points:

    When these points are reflected in your script, it becomes as follows.

    Modified script:

    From:

      values.forEach(function(row) {
        range.getCell(row,1).setBackground('red');
       
     });
    

    To:

    values.forEach(function (element,row) {
      range.getCell(row + 1, 1).setBackground('red');
    });
    

    Note:

    Reference: