0

我一直在尝试编写一个快速的谷歌脚本来计算婚礼邀请响应电子表格的 rsvps。该脚本完美地运行了一周,因为新条目被添加到电子表格中,然后突然停止工作,每个单元格中出现以下错误消息:

错误:服务超时:Apps 脚本

脚本本身很简单。它查询相关列(有多个事件),然后检查是否有用户指定的一些响应——通常是“是”、“否”或空白。

这个错误是什么意思,有没有人有任何修复建议?

function sumRSVP(response, rsvpType) {
  var rsvpCol = 7;
  if (rsvpType == "rehearsal") rsvpCol = 8;  
  if (rsvpType == "brunch") rsvpCol = 9;

  var mySum = 0;

  var sh = SpreadsheetApp.getActiveSheet();
  for( i=2; i<177; i++){

    var rsvp = sh.getRange(i, rsvpCol).getValue();
    var nguests = sh.getRange(i, 6).getValue();
    if(nguests != "" && rsvp == response){
      mySum = mySum + parseFloat(nguests);
    }
  }

  return mySum;
}
4

1 回答 1

4

Hopefully the wedding went well. This was asked some time ago but has been viewed over 300 times at this post and I believe is important:

Data should not be extracted from a spreadsheet in a loop. The data needed should be extracted in a batch to an array and the array evaluated in the loop.

See docs reference at: https://developers.google.com/apps-script/guide_common_tasks#OptimizeScripts

You can write scripts to take maximum advantage of the built-in caching, by minimizing the number of reads and writes. Alternating read and write commands is slow. To speed up a script, read all data into an array with one command, perform any operations on the data in the array, and write the data out with one command.

function sumRSVP(response, rsvpType) {
  var rsvpCol = 7;
  if (rsvpType == "rehearsal") rsvpCol = 8;  
  if (rsvpType == "brunch") rsvpCol = 9;

  var mySum = 0;

  var sh = SpreadsheetApp.getActiveSheet();
  // start at row 2 - uses columns 6-9
  var data = sh.getRange(2, 6, 177 - 1 , 4).getValues();
  for(var i=0; i<data.length; i++){

    var rsvp = data[i][rsvpCol - 6];
    var nguests = data[i][0];
    if(nguests != "" && rsvp == response){
      mySum = mySum + parseFloat(nguests);
    }
  }

  return mySum;
}
于 2012-05-11T20:46:01.607 回答