0

I am working with this script:

 /**  * Automatically sorts the 1st column (not the header row)
 Ascending.  */ function onEdit(event){   var sheet =
 event.source.getActiveSheet();   var editedCell =
 sheet.getActiveCell();

   var columnToSortBy = 3;   var tableRange = "A2:T99"; // What to
 sort.

   if(editedCell.getColumn() == columnToSortBy){   
     var range = sheet.getRange(tableRange);
     ran

ge.sort( { column : columnToSortBy, ascending: true } );   }

I need it to only run on Sheet 2, Sheet 3, Sheet 4, and not all sheet in the workbook. I tried doing several variation of getsheets that didn't work.

1

The name of the current sheet is obtained by sheet.getSheetName(). You want to make sure that this name is one of "Sheet 2", "Sheet 3", "Sheet 4". A concise way to express this condition is to have an array sheetList with the names that need to be sorted, and check whether the name of the active sheet is on the list. The method indexOf does this check: it returns -1 if the name is not on the list.

function onEdit(event) {
  var sheetList = ["Sheet 2", "Sheet 3", "Sheet 4"];
  var sheet = event.source.getActiveSheet();
  if (sheetList.indexOf(sheet.getSheetName()) != -1) {
    var editedCell = sheet.getActiveCell();
    var columnToSortBy = 3;   
    var tableRange = "A2:T99";      
    if (editedCell.getColumn() == columnToSortBy) {   
      var range = sheet.getRange(tableRange);
      range.sort( { column : columnToSortBy, ascending: true } );
    }
  }
}
  • this line returns a syntax error " if (sheetList.indexOf(sheet.getSheetName())) != -1) { – Justin Baker Aug 23 '17 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.