Google Sheets Apps 脚本获取整个 sheet 的范围,即使它没有数据

Google Sheets Apps Script get range of entire sheet even if it has no data

假设我定义了一个 sheet thissheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name),其中 name 是一个字符串,其中包含我的 sheet 之一的名称。

我知道如果我在sheet里有数据,我可以用thissheet.getDataRange()到select这一切。 或者,交替 thissheet.getRange(1,1,thissheet.getLastRow(),thissheet.getLastCol())

但是如果我想要整个 sheet selected 作为一个 运行ge 而不管它是否有数据呢?

或者,在我的特定情况下,我有 运行 thissheet.clear() 并清除了我 sheet 中的所有数据,但我需要使用 thissheet.somerange.removeCheckboxes() 其中 somerange 基本上将整个 sheet 表示为 Range 对象以清除所有留下的空复选框,因为 clear() 不清除复选框。

好的,所以首先我需要确保我的脚本序列中 运行 thissheet.dataRange().removeCheckboxes()thissheet.clear() 之前。只要我控制一切并遵守某些规则,这就有效。这仍然存在两个问题:

  1. 一旦我部署我的脚本并且其他用户开始使用它,有人很容易清除 sheet 并留下复选框,这将导致我的脚本崩溃稍后因为 .dataRange() 实际上将不是 运行ge.

  2. 如果我在最后一行或最后一列中有没有其他数据的复选框,它们仍然不会被清除,因为它们不会成为 .dataRange()[=25= 的一部分]

那么如何确保我的 sheet 中的所有复选框都已被删除?

1。删除 sheet.

中的所有复选框

在您的情况下,为了检索 sheet 中的所有单元格,使用 getMaxRowsgetMaxColumns 怎么样?当这反映在脚本中时,它变成如下。

const sheetName = "Sheet1"; // Please set the sheet name.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns());

range.removeCheckboxes().clear(); // Here, the checkboxes and cells are cleared.
  • 如果您只想删除复选框,请将 range.removeCheckboxes().clear() 修改为 range.removeCheckboxes()

2。选中 sheet.

中的复选框

为了确认是否在sheet中删除了所有复选框,下面的示例脚本怎么样?

const sheetName = "Sheet1"; // Please set the sheet name.

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns());

const checkCheckboxes = range.getDataValidations().flatMap((r, i) => r.flatMap((c, j) => c && c.getCriteriaType() == SpreadsheetApp.DataValidationCriteria.CHECKBOX ? {row: i + 1, col: j + 1} : []));
if (checkCheckboxes.length == 0) {

  console.log("No checkboxes in this sheet.");

} else {

  console.log("Checkboxes are existing in the cells.");
  console.log(checkCheckboxes); // Here, you can see the cell coordinates of the checkboxes.

}

注:

  • 例如,我认为Sheets API也可以用于你的情况。但我从你的问题中猜测,使用 Spreadsheet 服务可能是合适的。所以,我提出了以上答案。

参考文献:

出于所有意图和目的,复选框包含数据,无论是否选中。

也提到了这一点

Once I deploy my script and other users start using it, it would be fairly easy for someone to clear the sheet and leave the checkboxes behind and it will cause my script to crash later because .dataRange() will effectively be no range.

情况并非如此,因为如果找不到数据,.getDataRange() 将默认为 A1

If I have checkboxes in the last row or last column with no other data, they still won't get cleared because they won't be part of .dataRange()

复选框是数据范围的一部分。添加复选框时,默认包含 FALSE