循环文件夹,工作表和setFormula - 优化代码

时间:2018-06-19 08:55:53

标签: google-apps-script

我不确定这是否可以,但我正在学习编写脚本,我最近写了一个脚本,对我来说看起来非常复杂,我想知道你是否可以给我一些指示我如何制作更简单。

基本上,脚本从工作表中的B列获取名称,并打开具有该名称的每个文件夹。然后,它会找到具有相应名称(+一点额外)的电子表格,打开它,然后浏览每个工作表并在每个工作表中设置与定义的名称对应的公式。 当它在该表中具有setFormula时,它会更新该行中的列A,以便下次运行时,它知道已处理了多少文件以及从何处开始。我有数百个文件和文件夹,这就是我制作触发器的原因。

我做错了吗?

function changeFormula() {  
 var folders, regnskabFolder, mainSheet, targetLastRow, namesLastRow, w 
 whereToStart, whereToEnd, numNames, sheets, names, namesRange, range;

 regnskabFolder = DriveApp.getFolderById('ID');
 folders = regnskabFolder.getFolders();
 mainSheet = SpreadsheetApp.openById('ID').getSheetByName("Sheet1");

 names = [];
 namesRange = [];
 targetLastRow = mainSheet.getRange("A1:A").getValues();
 namesLastRow = mainSheet.getRange("B1:B").getValues()
 whereToStart = targetLastRow.filter(String).length+1;
 whereToEnd = namesLastRow.filter(String).length;
 if (whereToStart == 0) {var whereToStart = 1}
 else { whereToStart = whereToStart} 
 numNames = whereToEnd - whereToStart+1;
 if (numNames == 0) { numNames = 1}
 else {numNames = numNames}

 Logger.log(whereToEnd);
 Logger.log(whereToStart);

 if (whereToEnd + 1 > whereToStart) {
   ScriptApp.newTrigger("changeFormula")
   .timeBased()
   .after( 10*60 * 1000)
   .create();

   sheets = ["Januar","Februar","Marts","April","Maj","Juni","Juli","August","September","Oktober","November","December"];

   range = mainSheet.getRange(whereToStart, 2, numNames, 1).getValues();
   for (var i=0;i<range.length;i++){
     namesRange.push(range[i]);
   }
   Logger.log(namesRange) 
   while (folders.hasNext()) {
    var currentFolder=folders.next();
    var folderName = currentFolder.getName();
    var folderID = currentFolder.getId();
    names.push(folderName);
   for (var v = 0; v<namesRange.length; v++) {
    Logger.log(namesRange[v]);
    if(folderName == namesRange[v]) { 
     var folder2 = DriveApp.getFolderById(folderID);
     var files = folder2.getFiles();
     while (files.hasNext()) {
       var currentFile=files.next();
       var fileName = currentFile.getName();
       if (fileName == "Regnskab 2018 " + folderName || fileName == folderName + " Regnskab 2018" ) {
         var sheet = SpreadsheetApp.open(currentFile);       
         for (var i = 0; i<sheets.length; i++) {
          var sheet1 = sheet.getSheetByName(sheets[i]);
          sheet1.getRange("B4").setFormula('=sum(I13:I)');
         }
       }
       else {
         Logger.log(fileName); 
       }
     }
    }
    mainSheet.getRange(whereToStart+v, 1, 1, 1).setValue("'+");
    }
   }
  }
  else {
   var allTriggers = ScriptApp.getProjectTriggers();
   for (var i = 0; i < allTriggers.length; i++) {
     ScriptApp.deleteTrigger(allTriggers[i]);
   }
  }   
 }

0 个答案:

没有答案