使用脚本和 GID 更改 Google Sheet 标签名称

时间:2021-01-12 08:26:35

标签: google-apps-script google-sheets google-sheets-formula google-sheets-api

使用 google App 脚本,我尝试更改 google sheet 标签名称。但是,由于选项卡会定期更改名称,因此我们的想法是在脚本中使用 GID 来更改 ID。想象一下下面的表格:有一个表格,其中有一列是假定的工作表名称,然后是应该具有该名称的选项卡的 gid。

<头>
命名事件 GID
美国广播公司 1 月 12 日 981289394
BCD 1 月 18 日 901985265
ZYX 2 月 18 日 1085929622

这可能吗?这会是什么样子?

1 个答案:

答案 0 :(得分:1)

我认为可以使用 Google Apps 脚本使用“GID”(工作表 ID)更改工作表名称。在您的表中,当“Name Event”和“GID”分别是“A”和“B”列,并且该表与包含要重命名的工作表的电子表格相同时,以下脚本如何?< /p>

这个脚本的流程如下。

  1. 使用工作表中的 GID 检索用于重命名工作表名称的表。
  2. 创建一个用于搜索 GID 的对象。
  3. 使用从源工作表中检索到的 GID 重命名工作表名称。

在此示例脚本中,在您的表中,检索了第 1 列和第 2 列,并将第 2 列的值用作 GID 列表。并且,第一列的值用作您要重命名的工作表名称。

示例脚本:

请将以下脚本复制并粘贴到电子表格中,并设置包含问题中表格的工作表名称。使用此脚本时,请运行 myFunction。这样,从源工作表中检索值,并使用检索到的 Name EventGID 值重命名工作表。

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name of the sheet of your table in your question. This is a source sheet.

  // 1. Retrieve the table for renaming the sheet name using GID from the sheet.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const srcSheet = ss.getSheetByName(sheetName);
  const data = srcSheet.getRange("A2:B" + srcSheet.getLastRow()).getValues();

  // 2. Create an object for searching the GID.
  const sheetObj = ss.getSheets().reduce((o, sheet) => Object.assign(o, {[sheet.getSheetId()]: sheet}), {});

  // 3. Rename the sheet name using GIDs retrieved from the source sheet.
  data.forEach(([name, gid]) => {
    if (sheetObj[gid] && !ss.getSheetByName(name)) {
      sheetObj[gid].setName(name);
    }
  });
}

注意:

  • 在此示例脚本中,假设“Name Event”和“GID”分别是“A”和“B”列,并且具有 GID 的工作表与源工作表是相同的电子表格。请注意这一点。如果这与您的实际情况有差异,请告诉我。
  • 在 Google 电子表格中,不能在 Google 电子表格中创建相同的工作表名称。所以请注意这一点。

参考: