首页 > 解决方案 > 删除多个电子表格中的多个工作表

问题描述

1. 我正在尝试删除多个电子表格中的多个工作表。下面的代码适用于一张纸,但永远不会移动到下一张纸。我编辑了另一个循环遍历所有电子表格的脚本,所以我不确定我错在哪里。

2. 我的 lastRow 代码最后给出了一个空,当我执行 lastRow-1 时,它没有显示我的最后一行。我的代码,虽然它继续这样做,但在空行中出现错误。随着列表不时使用另一个脚本更新,我无法在此处设置固定范围。

此代码运行半小时后出现运行时错误。

function myFunction() {
  var dbsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ID Database");
  var IDList = dbsheet.getRange("B2:B").getValues(); 
  var lastRow = dbsheet.getLastRow();
//Looping through all the file ID's in the ID Database tab
  for (var i=0; i < lastRow; i++) {
  var destinationID = (IDList[i][0]);
//Locating the file
  var ss = SpreadsheetApp.openById(destinationID); 
//Below the steps that will be executed
  var sheets = ss.getSheets();

  for (i = 0; i < sheets.length; i++) {
     switch(sheets[i].getSheetName()) {
     case "Asset List":
     case "History":
     case "Floorplans":
         break;
     default:
        ss.deleteSheet(sheets[i]);
      }
    }
  }
}

我对 java 和脚本很陌生,我只是在尝试学习代码片段时反复试验。

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


由于要迭代的范围从第 2 行而不是第 1 行开始,因此您需要将lastRow变量减去 1 以匹配 IDList 数组的长度。主要问题是您i对两个循环使用相同的变量,您需要为每个循环使用不同的计数器变量,例如j内部循环:

function myFunction() {
  var dbsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ID Database");
  var IDList = dbsheet.getRange("B2:B").getValues(); 
  var lastRow = dbsheet.getLastRow();

  //Looping through all the file ID's in the ID Database tab
  for (var i=0; i < lastRow - 1; i++) {
    var destinationID = (IDList[i][0]);
    //Locating the file
    var ss = SpreadsheetApp.openById(destinationID); 
    //Below the steps that will be executed
    var sheets = ss.getSheets();

    for (var j = 0; j < sheets.length; j++) {
      switch(sheets[j].getSheetName()) {
        case "Asset List":
        case "History":
        case "Floorplans":
          break;
        default:
          ss.deleteSheet(sheets[j]);
      }
    }
  }
}

推荐阅读