将范围内容与其他范围对齐

时间:2018-03-14 15:09:38

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

data to be aligned

我想在名称(B和D列)的功能中对齐行,例如在图片(1)上,2个红色矩形应该在同一条线上,就像2个绿色矩形一样,但我不是知道原因,它不起作用,这里是代码:

function onOpen(event){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("test1");
  var data = sheet.getDataRange().getValues();

  for(var j = 1; j < data.length; j++) {
    if(data[j][1].trim() != '') {
      for (var i = 1; i < data.length; i++) {
        if(data[i][3].trim() != '') {
          if(data[j][1] == data[i][3]) {
            if(j != i) {
              var j1 = j + 1;
              var i1 = i + 1;
              sheet.getRange('D'+j1+':E'+j1).moveTo(sheet.getRange('F1:G1'));
              sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('D'+j1+':E'+j1));
              sheet.getRange('F1:G1').moveTo(sheet.getRange('D'+i1+':E'+i1));
            }
            break;
          }
        }
      }
    }
  }
}

我很确定这段代码应该可行

奇怪的是,如果我像这样一步一步地运行代码,首先是:

for(var j = 1; j < 2; j++) 

for(var j = 2; j < 3; j++) 

...

,直到

for(var j = 6; j < 7; j++) 

1 个答案:

答案 0 :(得分:0)

我找到了解决方法:)

function onOpen(event){
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var sheet = ss.getSheetByName("test1");
  var data = sheet.getDataRange().getValues();
  var blank = 0;

  // I count the blank case so I don't run the code effortlessly on blank case
  for(var j = 1; j < data.length; j++) {
    if(data[j][1].trim() == '')
      blank++;
  }
  var length = data.length - blank;

  // I don't make a real switch in fact, I'm using a tempory space where I order the data
  for(var j = 1; j < length; j++) {
    for (var i = 1; i < length; i++) {
      if(data[j][1] === data[i][3]) {
        var j1 = j + 1;
        var i1 = i + 1;
        sheet.getRange('D'+i1+':E'+i1).moveTo(sheet.getRange('F'+j1+':G'+j1)); // column F & G is the tempory space where I put the ordered data
        break;
      }
    }
  }

  // I move back the tempory space ordered now to his initial place
  sheet.getRange('F2:G'+length).moveTo(sheet.getRange('D2:E'+length));
}