Google Spreadsheet Script to Blink a range of Cell

2019-06-04 00:48发布

I'm New in scripting, Recently found the below script to make a cell flash or change color when edit. I would like to implement the same script but for a range of cells. I have tried ie: A7:A but it won't work. I believe I'm missing an argument somewhere.

function onEdit(e)
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mysheet = ss.getSheetByName("Sheet1");
  var activeCell = ss.getActiveCell().getA1Notation();

  if( activeCell == "A1" )
  {
    for(var i=0;i<50;i++)
    {
      if( i%2 == 0 )
        mysheet.getRange("A1").setBackground("RED");
      else
        mysheet.getRange("A1").setBackground("WHITE");

      SpreadsheetApp.flush();
      Utilities.sleep(500);
    }
  }
}

1条回答
放我归山
2楼-- · 2019-06-04 00:50

I understand you want the edited cell to flash if it's in the range A7:A. This is done below using the event object in which the range property refers to the active range.

If the column is 1 and row >= 7, flash 50 times. (This means 25 seconds of flashing, by the way.)

function onEdit(e) {
  if (e.range.getColumn() == 1 && e.range.getRow() >= 7) {
    for (var i = 0; i < 50; i++) {
      e.range.setBackground(i % 2 ? "WHITE" : "RED");
      SpreadsheetApp.flush();
      Utilities.sleep(500);
    }
  }
}

If you wanted the entire range A7:A to flash when any of its cells is edited, then the relevant method is setBackgrounds, and it takes a double array of colors. This array needs to be prepared first, so the code becomes

function onEdit(e) {
  if (e.range.getColumn() == 1 && e.range.getRow() >= 7) {
    var range = e.range.getSheet().getRange("A7:A");
    var height = range.getHeight();
    var whiteArray = Array.apply(null, Array(height)).map(function() {
      return ["WHITE"];
    });
    var redArray = Array.apply(null, Array(height)).map(function() {
      return ["RED"];
    });
    for (var i = 0; i < 50; i++) {
      range.setBackgrounds(i % 2 ? whiteArray : redArray);
      SpreadsheetApp.flush();
      Utilities.sleep(500);
    }
  }
}

using the array-filling method from this answer.

查看更多
登录 后发表回答