0

在这种情况下,我正在寻找一点帮助。我有一个电子表格,我在其中创建了一个新工作表,我将其重命名,一旦完成,我对大约 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"); 

}
4

1 回答 1

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")
  }
}
于 2012-10-31T07:33:27.593 回答