脚本超出了最大执行时间

时间:2019-01-11 03:12:27

标签: google-apps-script google-sheets

我正在使用脚本首先将所有终止产品的列表从工作表的“数据”标签复制到“终止标签”

“数据”标签如下所示

代码检查是否写入了结束日期 如果是的话-复制该行并将其粘贴到“终止”标签

所有行(大约2000条)都已完成

代码删除“数据”标签中所有带有结束日期的行

但是代码不是很有效并且数据量很大-我收到“超过最大执行时间”错误

function movingTerms() {
  var app = SpreadsheetApp ;
  var sheet1 =  app.getActiveSpreadsheet().getSheetByName("data") ;
  var sheet3 = app.getActiveSpreadsheet().getSheetByName("Terminations");

  var range1 = sheet1.getRange(2, 1, sheet1.getLastRow() - 1,9);
  var range3 = sheet3.getRange(2, 1, sheet3.getLastRow(), 9);

  var values1 = range1.getValues();
  var values3 = range3.getValues();
  var rowcount = sheet1.getLastRow();
  var row_deleted = 0; 

  for (var i = 0; i < (sheet1.getLastRow() - 1); i++) 
  {
    if (values1[i][4] !== "")     
    {
      var rowtodelete = sheet1.getRange(i + 2, 1, 1, 10);
      var rowtoadd = sheet3.getRange(sheet3.getLastRow() + 1, 1);
      rowtodelete.copyTo(rowtoadd);
    }
  }   

  for (var k = 0; k < values1.length; k++)
  {
    var row = k + 1 - row_deleted; 
    if (values1[k][4] !== "")       
    {
      var getridof  = row +1;
      sheet1.deleteRow(getridof);
      row_deleted++;
    } 
  }
}

1 个答案:

答案 0 :(得分:0)

我通常希望看到电子表格能够正确执行此操作,但这是我会执行的方式。

function movingTerms() {
  var ss=SpreadsheetApp.getActive();
  var sheet1=ss.getSheetByName("data") ;
  var sheet3=ss.getSheetByName("Terminations");
  var range1=sheet1.getRange(2, 1, sheet1.getLastRow()-1,9);
  var range3=sheet3.getRange(2, 1, sheet3.getLastRow(),9);//You don't really need this
  var values1=range1.getValues();
  var values3=range3.getValues();//You don't really need this
  var rowcount=sheet1.getLastRow();
  var rowsdeleted = 0; 
  for (var i=0;i<values1.length;i++) {
    if (values1[i][4]!="") {//column5
      var rowtodelete = sheet1.getRange(i-rowsdeleted+2, 1, 1, 10);
      var rowtoadd = sheet3.getRange(sheet3.getLastRow()+1,1);//You could also append to sheet 3 if you wish
      rowtodelete.copyTo(rowtoadd);
      sheet1.deleteRow(i-rowsdeleted+2);
      rowsdeleted++;
    }
  }
}