Make Cell Flash onOpen Instead of onEdit in Google Sheets

google sheetsgoogle-apps-scriptgoogle-apps-script-triggers

I need a Google sheets script which will make the background color of a cell flash. Currently I have a script which works fine, but onEdit. It would be far better in this case if the script could work onOpen, as I need the users attention to be drawn to a specific cell when they first open the sheet.

The sheet name is LBACC17, and the cell I need to flash (Change background colors) is K3.

I have very little scripting knowledge.

Here's the script I have now which works onEdit, which needs the code changing so will work onOpen…

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

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

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

Best Answer

The necessary changes are: replace onEdit with onOpen, and eliminate the check if( activeCell == "K2" ) as the script is no longer about the active cell.

I also shortened the script by replacing the inner conditional statement with a ternary operator.

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mysheet = ss.getSheetByName("LBACC17");
  var cell = mysheet.getRange("K3");
  for (var i = 0; i < 50; i++) {
    cell.setBackground(i % 2 ? "WHITE" : "RED");
    SpreadsheetApp.flush();
    Utilities.sleep(500);
  }
}