0

I am trying to figure out the official code sample of Google:

/**
 * The event handler triggered when the selection changes in the spreadsheet.
 * @param {Event} e The onSelectionChange event.
 */
function onSelectionChange(e) {
  // Set background to red if a single empty cell is selected.
  var range = e.range;
  if(range.getNumRows() === 1 
      && range.getNumColumns() === 1 
      && range.getCell(1, 1).getValue() === "") {
    range.setBackground("red");
  }
}

but I got the error message:

TypeError: Cannot read property 'range' of undefined...

Can somebody give me a hint? It is my first attempt with Google Apps Script.

Kos
  • 4,890
  • 9
  • 38
  • 42
  • 2
    Note this script requires an event object from a trigger, so you cannot run this code from the script editor. – Cooper Jul 30 '20 at 19:48
  • Does this answer your question? [Looking for an onEdit script that can be used to change the color of a google sheets cell when it is edited?](https://stackoverflow.com/questions/58546702/looking-for-an-onedit-script-that-can-be-used-to-change-the-color-of-a-google-sh) – TheMaster Jul 31 '20 at 08:56
  • Does this answer your question? [How can I test a trigger function in GAS?](https://stackoverflow.com/questions/16089041/how-can-i-test-a-trigger-function-in-gas) – Rubén Aug 02 '20 at 04:11

1 Answers1

0

If you use this code:

function onSelectionChange(e) {
  console.log(JSON.stringify(e));
}

This is what the event object looks like:

{"source":{},"range":{"columnEnd":31,"columnStart":31,"rowEnd":12,"rowStart":12},"user":{"email":"","nickname":""},"authMode":"LIMITED"}
Cooper
  • 59,616
  • 6
  • 23
  • 54