Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-apigoogle-apps-script-editor

Is there a function in Google Apps Script for selecting all columns to the left or right of a selected cell?


I'm currently making a script that would automatically sort a range of columns based on the alphabetical order of one specific column. However, more columns are expected to be added over time, and it would be a hassle to keep on updating the range. Is there a function or method to select all columns after a certain column?

function onEdit(event){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 2; // column as basis for sorting
  var tableRange = "B7:F"; // range of cells per row that will be sorted.

  if(editedCell.getColumn() == columnToSortBy){   
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: true } );
  }
}

Solution

  • There's a function called 'getLastColumn' and 'getLastRow' which will return the last column/row used. Try this line to get the range you're interested in:

    var tableRange = sheet.getRange(7, 2, sheet.getLastRow() - 6, sheet.getLastColumn() - 1);