简体   繁体   中英

sort empty cells to top

I am working on a google sheet to organize my school's locker assignment system. For unassigned lockers, the student/grade/major/etc. cells are blank. ideally i need a function that will sort the lockers to push all unassigned (blank student cells) to the top of the sheet. However, regardless of if i sort ascending or descending, google api seems to ignore any blank cells and pushes them to the bottom. Once this sheet is finished it will have close to 1000 lockers so it will be super annoying to have to scroll all the way down every time a teacher wanted to assign an open locker. any thoughts?

Since it seems hard to do with sheet native functions I tried the array approach and came up with the following code that seems to work as expected :

The functions can take a parameter (the number of the column -starting from 0 - you want to sort on) and has a default value set on G so that you can call it from the menu without parameters.

TEST SHEET HERE (test sorts on column A)

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Sort Sheet",
    functionName : "sortSheet"
  }];
  sheet.addMenu("Sort Sheet", entries);
};

function sortSheet(col){
  col = col || 6;// default to col G 
  Logger.log(col);
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var data = range.getValues();
  var headers = data.shift();
  data.sort(spaces);
  function spaces(x,y){
    var a = x[col];// choose the cell in the column
    var b = y[col];
    var comp = (a==''?"_":a)>(b==''?"_":b)?1:-1;// sort replacing empty with underscore
    return comp;
  }
  data.unshift(headers);// put back headers in place
  range.setValues(data);//update sheet
}

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