脚本大量使用方法

时间:2017-08-16 17:53:24

标签: google-apps-script google-sheets

我是使用Google Apps脚本的新手,对编程知之甚少。我想要做的是将特定列的值复制到不同的电子表格。这是我的代码:

function myFunction() {

  var ss = SpreadsheetApp.getActive();
  var responses = ss.getSheetByName("Responses ID");//Where ID's of the spreadsheets are listed.
  var consolidatedSheet = ss.getSheetByName("Consolidated");//Where the data should be pasted.

  var responseColValues = responses.getRange(2,2, responses.getMaxRows() -1).getValues();
  var responsesIds = [i for each (i in responseColValues)if (isNaN(i))];
  var ssSelected = SpreadsheetApp.openById(responsesIds[0]);
  var selectedSheets = ssSelected.getSheets();

  for (i=0; i<3; i++){

  var maxRows = selectedSheets[i].getLastRow()-1;
  var x=2, y=2;
  var lastRow = consolidatedSheet.getLastRow()+1;

    for (j=0; j<maxRows; j++){

      var eventID = selectedSheets[i].getRange(y,2).getValue();
      var employeeName = selectedSheets[i].getRange(y,3).getValue();
      var productionDate = selectedSheets[i].getRange(y,4).getValue();

      var consolidatedSheetCell = consolidatedSheet.getRange(lastRow,1).setValue(eventID);
      var consolidatedSheetCell = consolidatedSheet.getRange(lastRow,2).setValue(employeeName);
      var consolidatedSheetCell = consolidatedSheet.getRange(lastRow,3).setValue(productionDate);

      y++;
      lastRow++;

    }

  }

}

但是,我在执行提示(灯泡图标)上遇到此通知: screenshot of the message。我在想我的代码可以简化。我只是不确定该怎么做。提前谢谢。

1 个答案:

答案 0 :(得分:1)

.getRange()。getValue()和getRange.setValue()的每一行都是对文件的调用。由于你在for(){}循环中有这些,所以它们被多次调用。您的目标是将这些限制为尽可能少。既然你可以读写一个范围,你可以做类似的事情:

function myFunction() {

  var ss = SpreadsheetApp.getActive();
  var responses = ss.getSheetByName("Responses ID");//Where ID's of the spreadsheets are listed.
  var consolidatedSheet = ss.getSheetByName("Consolidated");//Where the data should be pasted.

  var responseColValues = responses.getRange(2,2, responses.getMaxRows() -1).getValues();
  var responsesIds = [i for each (i in responseColValues)if (isNaN(i))];
  var ssSelected = SpreadsheetApp.openById(responsesIds[0]);
  var selectedSheets = ssSelected.getSheets();

  for (i=0; i<3; i++){

  var maxRows = selectedSheets[i].getLastRow()-1;
  var y=2;
  var lastRow = consolidatedSheet.getLastRow()+1;

    var copyValues = selectedSheets[i].getRange(y,2, maxRows, 4).getValues();
    consolidatedSheet.getRange(lastRow,1, maxRows, 4).setValues(copyValues);


  }

}