【问题标题】:How to get the first row number after the last protected range of a Google Sheet using App Scripts如何使用 App Scripts 获取 Google Sheet 的最后一个受保护范围之后的第一行号
【发布时间】:2020-10-19 17:07:54
【问题描述】:
我正在尝试使用应用脚本获取 Google 表格的最后一个受保护范围之后的第一个行号。请注意,我的 Google 表格中有几个受保护的范围。我的代码如下但不工作?
var protections = sheetm.getProtections(SpreadsheetApp.ProtectionType.RANGE);
var len = protections.length; //last protection
var lastRow = protections[len].getRange().getLastRow();
var desiredRow = lowRow + 1;
【问题讨论】:
标签:
google-apps-script
google-sheets
【解决方案1】:
解释:
很遗憾,其他解决方案仅适用于某些情况。
protections 数组中的 last 保护对象并不意味着它包含工作表的最后一个受保护行。
请看下面的例子:
在屏幕截图中,有三个不同的受保护范围。
但是受保护的范围不是根据最后受保护的行进行排名的。也就是说,如果您计算此示例中每个范围的最后一个受保护行,您将得到:
[121.0, 18.0, 36.0]
这个数组的最后一个元素是36,但这不是工作表的最后一个受保护的行,实际上是121。
为了找到工作表的最后一个保护行,你需要找到每个保护范围的最后一个保护行,然后得到最大值:
const lastRows = [];
protections.forEach(pr=>lastRows.push(pr.getRange().getLastRow()));
const maxRow = Math.max(...lastRows);
解决方案:
function myFunction() {
const ss = SpreadsheetApp.getActive();
const protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
const lastRows = [];
protections.forEach(pr=>lastRows.push(pr.getRange().getLastRow()));
const maxRow = Math.max(...lastRows);
Logger.log(maxRow);
}
【解决方案2】:
您的代码很可能会抛出错误,因为集合和数组的 JavaScript 索引是基于 0 的。
尝试替换它
var len = protections.length; //last protection
var lastRow = protections[len].getRange().getLastRow();
通过
var len = protections.length; //last protection
var lastRow = protections[len - 1].getRange().getLastRow();