我相信你的目标如下。
- 第一行是使用命名范围的名称。
- 您想用新名称重命名命名范围。范围在列中的第 2 行之后。
- 您要选择工作表上的列
DATA VALIDATION。
- 您希望通过提供从第一行检索到的名称,将命名范围重命名为选定列的每一列。
对于这个,这个答案怎么样?
流程:
此示例脚本的流程如下。
- 检索工作表。
- 检索第一行值。
- 检索工作表中的命名范围并创建一个对象。
- 检索选择。
- 检索每个范围并使用名称重命名现有的命名范围。
示例脚本 1:
在此示例脚本中,为选定列重命名了现有命名范围。在运行脚本之前,请选择工作表DATA VALIDATION 中的列。然后,请运行脚本。这样,使用第一行检索到的名称为每一列设置命名范围。
function Group_A() {
// 1. Retrueve sheet.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("DATA VALIDATION");
// 2. Retrieve the 1st row values.
const headerRow = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
// 3. Retrieve the named ranges in the sheet and create an object.
const namedRangesObj = sheet.getNamedRanges().reduce((o, e) => Object.assign(o, {[e.getRange().getColumn()]: e}), {});
// 4. Retrieve the selection.
const selection = sheet.getSelection();
// 5. Retrieve each range and rename the existing named range using the name.
selection
.getActiveRangeList()
.getRanges()
.forEach(r => {
const col = r.getColumn();
const name = headerRow[col - 1];
if (!name) throw new Error("No headef value.");
if (col in namedRangesObj) {
namedRangesObj[col].setName(name);
}
});
}
示例脚本 2:
在此示例脚本中,为选定列重命名了现有命名范围。此外,当所选列不是命名范围时,使用从第一行检索的名称将其设置为新命名范围。在运行脚本之前,请选择工作表DATA VALIDATION 中的列。然后,请运行脚本。这样,使用第一行检索到的名称为每一列设置命名范围。
function Group_A() {
// Ref: https://stackoverflow.com/a/21231012/7108653
const columnToLetter = column => {
let temp,
letter = "";
while (column > 0) {
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
};
// 1. Retrueve sheet.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("DATA VALIDATION");
// 2. Retrieve the 1st row values.
const headerRow = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
// 3. Retrieve the named ranges in the sheet and create an object.
const namedRangesObj = sheet.getNamedRanges().reduce((o, e) => Object.assign(o, {[e.getRange().getColumn()]: e}), {});
// 4. Retrieve the selection.
const selection = sheet.getSelection();
// 5. Retrieve each range and rename and set the named range using the name.
selection
.getActiveRangeList()
.getRanges()
.forEach(r => {
const col = r.getColumn();
const name = headerRow[col - 1];
if (!name) throw new Error("No headef value.");
if (col in namedRangesObj) {
namedRangesObj[col].setName(name);
} else {
const colLetter = columnToLetter(col);
ss.setNamedRange(name, sheet.getRange(`${colLetter}2:${colLetter}`));
}
});
}
注意:
- 在这些示例脚本中,它假定每个命名范围是一列。请注意这一点。
- 请使用此脚本启用 V8。
参考资料: