如何在这种情况下循环

时间:2012-10-31 06:59:22

标签: google-apps-script

我正在寻找这种情况的一点帮助。我有一个电子表格,我在其中创建一个新工作表,我重命名它,一旦完成,我就像大约10个其他电子表格一样,我想知道如何实现一个for或while循环,所以我没有输入重复的代码10次。我的代码如下,任何帮助都会非常感激。我在另一个文档中有键,所以基本上我需要知道如何能够读取变量中的键,然后才能读取每个键,因为它们位于垂直列中。

function create(){
var ss0 = SpreadsheetApp.getActiveSpreadsheet();
ss0.setActiveSheet(ss0.getSheetByName("old"));
ss0.setActiveSheet(ss0.duplicateActiveSheet());
ss0.renameActiveSheet("main");
var ss0 = SpreadsheetApp.getActiveSpreadsheet();
ss0.getRange("A4:I500").clearContent();


    //repeated code key 1
var ss0 = SpreadsheetApp.getActiveSheet();
var master = SpreadsheetApp.openById("key1");
ss0.copyTo(master);
var ss0 = SpreadsheetApp.getActiveSpreadsheet();
master.setActiveSheet(master.getSheetByName("Copy of main"));
master.renameActiveSheet("main"); 


    // key 2
var ss0 = SpreadsheetApp.getActiveSheet();
var master = SpreadsheetApp.openById("key2");
ss0.copyTo(master);
var ss0 = SpreadsheetApp.getActiveSpreadsheet();
master.setActiveSheet(master.getSheetByName("Copy of main"));
master.renameActiveSheet("main"); 

}

1 个答案:

答案 0 :(得分:2)

您需要获取数组中的键并循环遍历此数组。

这是一个大纲

function myFunction() {
  //get the keys in an array
  //say, they are in column A in a spreadsheet from A1:A10
  var keyArray = SpreadsheetApp.openById("ID of the ss with key").getSheetByName("name of the sheet with key")
      .getRange("A1:A10").getValues();

  var ss0 = SpreadsheetApp.getActiveSheet();

  //loop for all the spreadsheets
  for(var i in keyArray){
    var ss = SpreadsheetApp.openById(keyArray[i][0]);
    ss0.copyTo(ss);
    ss.getSheetByName("Copy of main").setName("main")
  }
}