Google Sheets – Apply Script to Every Sheet Except First

google sheetsgoogle-apps-script

I've been working on a shared Google spreadsheet on Google Drive. The document has different sheets with a "Last Modified Date" Cell. I found an script for this to be auto-filled searching here:

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  var r = s.getActiveCell();
  if( r.getColumn() != 2 ) { //checks the column
    var row = r.getRow();
    var time = new Date();
    time = Utilities.formatDate(time, "GMT-08:00", "MM/DD/yy, hh:mm:ss");
    SpreadsheetApp.getActiveSheet().getRange('B' + row.toString()).setValue(time);
  };
};

The script works perfectly, I just changed the column and it worked! The thing is, I need to apply this script to every sheet but the first one. How can I deactivate the use of the script in the first sheet?

Best Answer

You can test if the active sheet is the first sheet with

sheet.getIndex() == 1

(doc)

So your function can be

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  if (s.getIndex() == 1) {
     return; // Don't do anything for first sheet
  }
  var r = s.getActiveCell();
  if( r.getColumn() != 2 ) { //checks the column
    var row = r.getRow();
    var time = new Date();
    time = Utilities.formatDate(time, "GMT-08:00", "MM/DD/yy, hh:mm:ss");
    SpreadsheetApp.getActiveSheet().getRange('B' + row.toString()).setValue(time);
  };
};