如何按字母顺序对Google表格的每一行进行排序

时间:2017-03-15 00:56:54

标签: google-apps-script

说我有一个范围,“A3:C5”这样:

  1. Bob,Cob,Rob

  2. Joe,Foe,Boe

  3. Jack,Back,Sack

  4. 我希望在Google表格中重新格式化

    1. Bob,Cob,Rob

    2. Boe,Foe,Joe

    3. Back,Jack,Sack

    4. 换句话说,我希望数据只按字母顺序排列在它们所在的行中。我不能为我的生活弄清楚如何在谷歌应用程序脚本中执行此操作,是否有人能够提供帮助?

1 个答案:

答案 0 :(得分:0)

快速谷歌搜索:

Tested and it works

function sortHorizontal()
{

  var startCol = 1;              // left-most column to where the sort will be applied; A = 1, B = 2, C = 3 etc
  var startRow = 1;              // first row to apply the sort
  var sheetName = 'Sheet1';      // name of sheet in which sort will be applied

  var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  var d = s.getDataRange().getValues();
  var output = [], temp;
  for (var i = startRow - 1; i < d.length; i++)
  {
    temp = d[i].slice(startCol - 1);
    temp.sort(ascSort);          // change to descSort for Z -> A sort
    output.push(temp);
  }
  s.getRange(startRow, startCol, output.length, output[0].length).setValues(output);
}


function ascSort(a, b)
{
  return ((a == b) ? 0 : (a && (!b || a < b)) ? -1 : 1);
}


function descSort(a, b)
{
  return ((a == b) ? 0 : (a > b) ? -1 : 1);
}