Answers / Question 25

Apps Script onEdit: "TypeError: Cannot read properties of undefined (reading 'range')" and e.value undefined on paste

Why onEdit(e) throws "Cannot read properties of undefined (reading 'range')" when you press Run, why e.value is undefined when several cells change, and a tested onEdit that handles pasted blocks plus a test function that runs it from the editor.

The problem

You paste an onEdit(e) script, press Run to try it, and get TypeError: Cannot read properties of undefined (reading 'range') (or 'source', or 'value'). Or the script works when you type in one cell, but does nothing when someone pastes a block, fills a column down, or deletes several cells at once.

Inspired by a public question on Stack Overflow. The problem above is described in our own words and the solution below is ours.

Why it happens

The fix: guard the event and read the cells yourself

The script below does a common job (when Status in column C becomes Done, write the date in column D, and clear it if Status changes back) in a way that survives both problems. It returns early with a hint if there's no event, ignores e.value, and reads every edited row from e.range, so pasted and filled blocks work. It reads and writes the block in one call each, which keeps it fast.

  1. Extensions → Apps Script, paste the code and set WATCH (tab name, Status column, the value, the date column).
  2. Save. Don't press Run on onEdit; it runs by itself on every edit.
  3. To try it from the editor, select one or more Status cells in the sheet, then choose testOnEdit in the function menu and press Run. It hands onEdit the same kind of event a real edit would.
Code.gsApps Script
// onEdit that survives the two classic errors:
//  1. "TypeError: Cannot read properties of undefined (reading 'range')" when you press Run:
//     there is no edit, so there is no event object. Use testOnEdit() below instead.
//  2. e.value is undefined when more than one cell changed (paste, fill down, delete a block).
//     So never trust e.value; read the edited cells from the sheet.
// Example job: when Status (C) becomes "Done", write the date in Completed (D); clear the date
// again if Status changes to anything else.
const WATCH = {
  sheet: 'Tasks',      // tab to watch
  column: 3,           // C: the Status column
  value: 'done',       // compared case-insensitively, spaces trimmed
  stampColumn: 4,      // D: where the date goes
  headerRows: 1        // rows at the top to ignore
};

function onEdit(e) {
  if (!e || !e.range) {                       // pressed Run in the editor: no event object
    console.log('onEdit only gets an event from a real edit. Run testOnEdit() to try it.');
    return 0;
  }
  const range = e.range, sheet = range.getSheet();
  if (sheet.getName() !== WATCH.sheet) return 0;
  if (range.getColumn() > WATCH.column || range.getLastColumn() < WATCH.column) return 0;  // didn't touch C
  const first = Math.max(range.getRow(), WATCH.headerRows + 1), last = range.getLastRow();
  if (last < first) return 0;
  const n = last - first + 1;
  const status = sheet.getRange(first, WATCH.column, n, 1).getValues();     // works for 1 cell or 500
  const stampRange = sheet.getRange(first, WATCH.stampColumn, n, 1);
  const stamps = stampRange.getValues();
  let changed = 0;
  for (let i = 0; i < n; i++) {
    const s = String(status[i][0]).trim().toLowerCase();
    if (s === WATCH.value && stamps[i][0] === '') { stamps[i][0] = new Date(); changed++; }
    else if (s !== WATCH.value && stamps[i][0] !== '') { stamps[i][0] = ''; changed++; }
  }
  if (changed) stampRange.setValues(stamps);  // one write for the whole block
  return changed;
}

// Run THIS from the editor. Select a Status cell (or several) first; it hands onEdit
// the same kind of event a real edit would.
function testOnEdit() {
  const ss = SpreadsheetApp.getActive();
  const range = ss.getActiveRange();
  const single = range.getNumRows() === 1 && range.getNumColumns() === 1;
  const event = { source: ss, range: range };
  if (single) event.value = String(range.getValue());   // like a real edit: value only for one cell
  console.log('onEdit changed ' + onEdit(event) + ' row(s)');
}

Finding the real error

The best test is a real edit: change a cell, then open Executions (the list icon on the left of the Apps Script editor). Every triggered run is listed there, with the actual error in red if it failed. Add console.log(JSON.stringify(e)) at the top of the function while testing to see exactly what the event contained, then remove it.

Good to know

The script's logic is unit-tested against a simulated spreadsheet before publishing. Always try new automations on a copy of your sheet first.