【问题标题】:How to make for loop script more efficient?如何使 for 循环脚本更高效?
【发布时间】:2018-01-03 11:04:00
【问题描述】:

总的来说,我对脚本编写非常陌生,尤其是在 GAS 方面,并且希望确保我能养成良好的习惯。我写了一个 for 循环脚本,它本质上做了以下事情:

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

例如

单元格 A1 包含“某物”。单元格 B1 包含“令人兴奋”

单元格 A2 包含“新”。单元格 B2 包含“X”

单元格 A3 包含“新建”。单元格 B3 包含“Y”

由于 A3 与单元格 A2 具有相同的值(该值为“新”),因此单元格 B3(当前值为“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});
  }
 }
}

谢谢你

【问题讨论】:

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


    【解决方案1】:

    最大的问题是您在每个循环中都会获得三个新范围。有一种方法可以做到这一点,而无需在循环中获得新的范围。您需要获取 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});
        }
      }
    }
    

    【讨论】:

    • 哦,我明白了 - 因此,我没有像最初那样单独定义每个范围,而是定义将首先使用的整个范围,然后在该范围内单独定义动作。我可以看到我最初所做的事情会花费这么长时间。 @Sandy 好,你太棒了!非常感谢:-)
    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2018-05-25
    • 2022-11-10
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多