Google工作表对特定工作表进行排序

时间:2015-12-27 15:41:49

标签: google-apps-script scripting google-sheets

表1 = SVerB-leden

第1列需要自动排序

表2 = Verjaardag

第2列需要自动排序。

我找到了一个脚本,可以在编辑时按字母顺序自动对给定列进行排序。但我想要在第一列上分类1张纸,在2号纸上分类另一张纸。

我发现的脚本适用于所有工作表。 是否有可能以一种有效的方式改变它?

 /**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 6;
  var tableRange = "B2:V500"; // What to sort.

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

2 个答案:

答案 0 :(得分:0)

试试这个:

function onEdit(event){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var editedCell = sheet.getActiveCell();
  var rngEdited = event.range;
  var sheetBeingEdited = rngEdited.getSheet().getName();
  Logger.log('rngEdited: ' + rngEdited);
  Logger.log('sheetBeingEdited: ' + sheetBeingEdited);

  var colEdited = editedCell.getColumn();
  var columnToSortBy;
  var tableRange;

  if (sheetBeingEdited === 'SVerB-leden') {
    columnToSortBy = 1;
    tableRange = "B2:V500"; // What to sort.
    if (colEdited === columnToSortBy) {
      sortColumn(columnToSortBy, tableRange, sheet);
    };
  } else if (sheetBeingEdited === 'Verjaardag') {
    columnToSortBy = 2;
    tableRange = "B2:V500"; // What to sort.
    if (colEdited === columnToSortBy) {
      sortColumn(columnToSortBy, tableRange, sheet);
    };
  };  
};

function sortColumn(colNmbr, rngToSort, sh) {
  var range = sh.getRange(rngToSort);
  range.sort( { column : colNmbr, ascending: true } );
};

答案 1 :(得分:-1)

此子项目在我的所有项目中均有效

function AutoSortOnEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
    ss.sort(1, false);   // Sorting by 1st column, change to 2 for the second //
  });
}