1

我有我们公司的时间表电子表格,我需要按每个时间表块(15 行 x 20 列)对员工进行排序。我有以下代码,我得到了帮助,但是一旦遇到没有员工姓名的块,数组就会退出排序(我希望这些被洗牌到底部)。我遇到的另一个问题是这些单元格中有许多公式,当我按原样运行它时,它会删除它们。如果可能的话,我想保持这些完好无损。这是代码:

function sortSections() 
{
  var activeSheet = SpreadsheetApp.getActiveSheet();
  //SETTINGS
  var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted
  var headerRows = 53; //number of header rows
  var pageHeaderRows = 5; //page totals to top of next emp section
  var sortColumn = 11; //index of column to be sorted by; 1 = column A
  var pageSize = 65;
  var sectionSize = 15; //number of rows in each section

  var col = sortColumn-1;
  var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
  var data = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn()).getValues();
  var data3d = [];
  var dataLength = data.length/sectionSize;
  for (var i = 0; i < dataLength; i++) {
    data3d[i] = data.splice(0, sectionSize);
  }
  data3d.sort(function(a,b){return(((a[0][col]<b[0][col])&&a[0][col])?-1:((a[0][col]>b[0][col])?1:0))});
  var sortedData = [];
  for (var k in data3d) {
    for (var l in data3d[k]) {
      sortedData.push(data3d[k][l]);
    }
  }
  sheet.getRange(headerRows+1, 1, sortedData.length, sortedData[0].length).setValues(sortedData);
4

1 回答 1

1

我认为可以使用Range.sort函数而不是自定义代码来解决您的问题。排序函数也重新定位公式,但以一种棘手的方式 - 如果单元格公式包含单元格引用,排序函数将重新定位单元格中的行索引更改为具有新的单元格行索引,例如,最初单元格C1包含=A1*B1公式,排序操作后,第 1 行重新定位到第 3 行,单元格“C3”将包含 not =A1*B1,但是=A3*B3

通过此修改,您的代码应如下所示

function sortSections() 
{
  var activeSheet = SpreadsheetApp.getActiveSheet();
  //SETTINGS
  var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted
  var headerRows = 53; //number of header rows
  var pageHeaderRows = 5; //page totals to top of next emp section
  var sortColumn = 11; //index of column to be sorted by; 1 = column A
  var pageSize = 65;
  var sectionSize = 15; //number of rows in each section

  var col = sortColumn-1;
  var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
  var range = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn());
  range.sort({column: sortColumn, ascending: true});
  ...
}
于 2012-08-31T06:41:26.163 回答