How to make onEdit() trigger function apply to multiple sheets

For future readers, the code snippet in Paul’s question is derived from code on the Google Docs help forum, which includes a detailed line-by-line explanation.

The function uses the variable sheetToWatch to identify one sheet (aka “tab”) that the onEdit() function cares about. That is validated by this comparison:

|| e.source.getActiveSheet().getName() !== sheetToWatch

…and if the source of the current trigger event is not matched, the function exits without doing anything.

What do I need to change? If you want this function to work on all sheets in the Spreadsheet, then you can just eliminate this check altogether:

function onEdit(e) {

    var columnToWatch = 1,
        columnToStamp = 2;               //change all of these to your needs

    if (e.range.columnStart !== columnToWatch
      || !e.value)
        return;
    e.source.getActiveSheet()
        .getRange(e.range.rowStart, columnToStamp)
        .setValue(new Date());
}

If you want to have the onEdit() operate on a set of sheets, then you can change that above comparison to check if the current sheet’s name is found in an array of sheet names. That will change the comparison to this:

  || sheetsToWatch.indexOf( e.source.getActiveSheet().getName() ) === -1 

You can learn more about the indexOf() method here. What it’s doing though, is getting the name of the event trigger source sheet, finding it in the sheetsToWatch array, and returning the found index. If the sheet does not appear in the array, indexOf() returns -1.

The resulting function is:

function onEdit(e) {

    var sheetsToWatch= ['Wrong Grading',
                        'Something Else'],
        columnToWatch = 1,
        columnToStamp = 2;            //change all of these to your needs

    if (e.range.columnStart !== columnToWatch
      || sheetsToWatch.indexOf( e.source.getActiveSheet().getName() ) === -1 
      || !e.value)
        return;
    e.source.getActiveSheet()
        .getRange(e.range.rowStart, columnToStamp)
        .setValue(new Date());
}

Leave a Comment