javascript - 删除多个电子表格中的多个工作表
问题描述
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 和脚本很陌生,我只是在尝试学习代码片段时反复试验。
解决方案
由于要迭代的范围从第 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]);
}
}
}
}
推荐阅读
- json - 深度嵌套 obj 的 Normalizr 用法
- java - 如何避免在使用 Maps 时重复使用 put() 方法?
- c# - 为什么 GenerateFunctions 找不到 System.Runtime, Version=4.2.1.0 并抛出 FileNotFoundException)?
- ansible - Jinja2 语法错误:预期标记“打印语句结束”
- reactjs - Redux 未采取行动
- tensorflow - 张量流中的常规模型检查点和保存的模型有什么区别?
- raspberry-pi - RaspberryPi 上的 Pharo:启动时未找到模块
- r - 如果字符串与向量中的最后一个和下一个不同,则替换它
- php - PHP 标头重定向,如果变量则重定向
- r - R:在 R 函数中使用 Lubridate ymd() 时出现日期解析错误,相同的代码在我编写的函数之外工作