使用 google App 脚本,我尝试更改 google sheet 标签名称。但是,由于选项卡会定期更改名称,因此我们的想法是在脚本中使用 GID 来更改 ID。想象一下下面的表格:有一个表格,其中有一列是假定的工作表名称,然后是应该具有该名称的选项卡的 gid。
命名事件 | GID |
---|---|
美国广播公司 1 月 12 日 | 981289394 |
BCD 1 月 18 日 | 901985265 |
ZYX 2 月 18 日 | 1085929622 |
这可能吗?这会是什么样子?
答案 0 :(得分:1)
我认为可以使用 Google Apps 脚本使用“GID”(工作表 ID)更改工作表名称。在您的表中,当“Name Event”和“GID”分别是“A”和“B”列,并且该表与包含要重命名的工作表的电子表格相同时,以下脚本如何?< /p>
这个脚本的流程如下。
在此示例脚本中,在您的表中,检索了第 1 列和第 2 列,并将第 2 列的值用作 GID 列表。并且,第一列的值用作您要重命名的工作表名称。
请将以下脚本复制并粘贴到电子表格中,并设置包含问题中表格的工作表名称。使用此脚本时,请运行 myFunction
。这样,从源工作表中检索值,并使用检索到的 Name Event
和 GID
值重命名工作表。
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);
}
});
}