Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dials-Mavis/70ffb45508ac85755fac6af0b351c267 to your computer and use it in GitHub Desktop.
Save Dials-Mavis/70ffb45508ac85755fac6af0b351c267 to your computer and use it in GitHub Desktop.
Gogle App Script: Sort all rows with data (excluding header row), ascending, by two columns, taking two column header names in case the columns are rearranged.
// This function gets column numbers by the header name
function getColumnNrByName(sheet, name) {
var range = sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var values = range.getValues();
for (var row in values) {
for (var col in values[row]) {
if (values[row][col] == name) {
return parseInt(col);
}
}
}
throw 'failed to get column by name';
}
// This function sorts a Spreadsheet (the first sheet) by two columns named "Platform" and "Team", ascending, ignoring the header row
function sortSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get the current spreadsheet
var sheet = ss.getSheets()[0]; // Get the first sheet
var headerRowNumber = 1; // Define the header row number
var range = sheet.getDataRange().offset(headerRowNumber, 0, sheet.getLastRow() - headerRowNumber); // get entire range of rows and columns that have data in them, excluding the header row
var column_1 = getColumnNrByName(sheet, 'Platform') + 1; // Set the name of the 1st column to sort
var column_2 = getColumnNrByName(sheet, 'Team') + 1; // Set the name of the 2nd column to sort
range.sort([{column: column_1, ascending: true}, {column: column_2, ascending: true}]); // sort the range of data-filled cells by the two columns
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment