Google表格脚本按列排序,然后按第2列排序

时间:2017-10-25 09:24:13

标签: google-apps-script google-sheets

我尝试按第2列(星级)排序范围(总共3列),然后按第3列(级别到级别)排序,然后按第1列(Bot)排序,这里是当前脚本我只是用它来排序第2列:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("DarkestSpawn");
var range = sheet.getRange("AD12:AF51");
var sortCol=1; // 0 for first column and 1 for second column and so on...
var asc=false; // set variable asc to false for descending sort

function onEdit(e) {
  sortrange();
};

function sortrange() {  
  var activeSheet = ss.getActiveSheet();
  var activeRange = activeSheet.getActiveRange();
  var sortedValues;
  if( sheet.getName() == activeSheet.getName() &&
    activeRange.getLastRow() >= range.getRow() && 
      activeRange.getRow() <= range.getLastRow() &&
        activeRange.getLastColumn() >= range.getColumn() && 
          activeRange.getColumn() <= range.getLastColumn() )
          { 
            sortedValues=range.getValues().sort(mySortFunction);
            range.setValues(sortedValues);
          }
};

var mySortFunction = function(a,b) {
  try{x=a[sortCol].toLowerCase();
      y=b[sortCol].toLowerCase();}
  catch(e){x=a[sortCol];y=b[sortCol];}
  return (x>y)?(asc?1:-1):(x<y)?(asc?-1:1):0
};

这是之前的例子,之后我想做:

Before After

2 个答案:

答案 0 :(得分:2)

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("DarkestSpawn");
var range = sheet.getRange("AD12:AF51");

function onEdit(e)  {
  range.sort([{column: 31, ascending: false}, {column: 32, ascending: false}, {column: 30, ascending: true}]);
}

这就是我最终得到的结果。经过多次试验和错误后,重新阅读排序参考和上面的代码,我得到了它,并最终工作。

感谢!!!!

答案 1 :(得分:0)

这是针对您的特定纸张和范围。我还附上了一个新的测试电子表格。

function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("DarkestSpawn");  
var sheet=e.source.getActiveSheet().getName() 
var range=s.getRange("AD12:AF51")
var col =e.range.getColumn() 
var actRow=e.range.getRow() 
var sortFirst=30
var sortSecond=31
var sortThird=32
var sortFirstAsc=true
var sortSecondAsc=false
var sortThirdAsc=false

if(sheet=="DarkestSpawn" && col==30 && actRow >= 12 && actRow <= 51 || sheet=="DarkestSpawn" && col==31 && actRow >= 12 && actRow <= 51 ||sheet=="DarkestSpawn" && col==32 && actRow >= 12 && actRow <= 51){
    range.sort([ {column: sortSecond, ascending: sortSecondAsc},{column: sortThird, ascending: sortThirdAsc},{column: sortFirst, ascending: sortFirstAsc}]);  
}}

这是我的测试电子表格。 https://docs.google.com/spreadsheets/d/1LGdDsmk9_ciZ9fXZ-KjxcOrJspadNGU9dONhrkQytQM/edit?usp=sharing