简体   繁体   中英

Why will this Google apps script only work if I hard-code the range?

I need to make a few sheets in a google doc stay continuously sorted by the first column (a timestamp). That seems easy enough, and my script works, but only if I hard-code range as shown below...I am tryin to figure out why it doesn't work when I use getLastRow() & getLastColumn() to give he range...see commented-out code below. If I uncomment it, this code no longer works. Why?

  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();
  var columnToSortBy = 1;
  var tableRange = "A2:Z99";
  if(editedCell.getColumn() == columnToSortBy && /^Form\sResponses/.test(sheet.getSheetName())){  
    var range = sheet.getRange(tableRange);
    /* WHY DOESN'T THIS WORK -- var range = sheet.getRange(2,1,sheet.getLastRow(), 
sheet.getLastColumn()-1); */
    range.sort( { column : columnToSortBy , ascending:false});
  };
};```


Approach:

Using the functions .getLastColumn() and .getLastRow() you will get respectively the positions of the last column and row that have content. You can use these position to build your range dynamically with the function .getRange(row, column, numRows, numColumns) .

Since you want to obtain the range "A2:Z99" this will translate in: .getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()) ;

Solution:

var sheet = event.source.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 1;
//var tableRange = "A2:Z99";
if(editedCell.getColumn() == columnToSortBy && /^Form\sResponses/.test(sheet.getSheetName())){  
   //var range = sheet.getRange(tableRange);
   var range = sheet.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()); // A2:Z99
   range.sort( { column : columnToSortBy , ascending:false});
}; 

References:

Sheet getRange(row, column, numrows, numcloumns)

Sheet getLastRow()

Sheet getLastColumn()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM