如何使循环脚本更有效?

时间:2018-01-02 22:45:56

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

我对一般的脚本写作非常陌生,特别是在GAS中,并且想确保我学习好习惯。我编写了一个for循环脚本,实质上是执行以下操作:

  1. 从第2行开始阅读第A栏
  2. 如果for循环中当前单元格上方的单元格值相同,则清除当前单元格右侧相邻单元格的内容。
  3. 例如

    Cell A1包含" Something"。单元格B1包含"令人兴奋的"

    单元格A2包含"新"。单元格B2包含" X"

    Cell A3包含" New"。单元格B3包含" Y"

    由于A3具有与单元格A2相同的值(该值为"新"),因此单元格B3(当前值为#34; Y")被清除,因此单元格中没有值B3。

    似乎需要很长时间才能运行,我确信这是由于我的新手写作,我希望尽可能高效地使用此脚本。

    你们中的任何人都有任何建议让这个脚本更有效率吗?

    我也很感激任何解释,为什么任何建议对我自己的理解会更有效率,以便以后碰巧找到这个帖子的任何人也可以理解它。

    这是脚本:

    function testCode() {
     var ss = SpreadsheetApp.getActiveSpreadsheet();
     var sheet = ss.getSheetByName("Test 1");
     var source = sheet.getRange("A2:A");
    
     for (i = 2; i < source.getLastRow(); i++) {
     var currentCell = sheet.getRange(i,1).getValue();
     var cellAbove = sheet.getRange(i-1,1).getValue();
     var cellRight = sheet.getRange(i,2);
     if (currentCell == cellAbove){
     cellRight.clearContent(),({contentsOnly:true});
      }
     }
    }
    

    谢谢你

1 个答案:

答案 0 :(得分:0)

最大的问题是你在每个循环中获得三个新范围。有一种方法可以在循环中获得新范围。您需要在A列和B列中获取数据。

function testCode() {
  var cellAbove,currentCell,cellRight,data,lastRow,L,sheet,source,ss;

  ss = SpreadsheetApp.getActiveSpreadsheet();
  sheet = ss.getSheetByName("Test 1");
  lastRow = sheet.getLastRow();

  source = sheet.getRange(2,1,lastRow-1,2);//Get data starting in row 2 and column 1
  //Get the number of rows that are the lastRow minus the number of rows not included 
  //at the top - get 2 columns

  data = source.getValues();//Get a 2D array of values
  L = data.length;//Get the number of elements in the outer array- which is the number of
  //rows in the array

  for (var i = 0; i < L; i++) {

    if (i == 0) {continue;} //If this is the first loop there is no value above it to check

    currentCell = data[i][0];
    cellAbove = data[i-1][0];

    if (currentCell == cellAbove){
      cellRight = sheet.getRange(i+1,2);
      cellRight.clearContent(),({contentsOnly:true});
    }
  }
}
相关问题