我发现这段代码是由 --Hyde 编写的,我了解它的一半工作原理,但它工作得很好。如果 B 列的一个单元格不为空,则触发在 A 列的一个单元格中创建复选框。我试图充分理解它,使其不仅依赖于一列,而且依赖于三列(B、C 和 D)。我知道“specs”常量需要更改以添加其他两列,并且“spec”常量需要遵循该常量。我还知道“checkboxCell”常量不会改变。我已经摆弄过他们但没有成功。
有人可以启发我吗?
/**
* Simple trigger that runs each time the user hand edits the spreadsheet.
* Inserts and removes checkboxes depending on whether another column is blank.
*
* @param {Object} e The onEdit() event object.
*/
function onEdit(e) {
// version 1.1, written by --Hyde, 30 December 2022
// - see https://webapps.stackexchange.com/q/153531/269219
if (!e) throw new Error('Please do not run the onEdit(e) function in the script editor window.');
const specs = [
{ sheet: "sheet_name", column: 2, rowStart: 2, checkboxColumn: 1, },
];
let sheet;
const spec = specs.filter(spec =>
spec.column === e.range.columnStart
&& (sheet = e.range.getSheet()).getName().match(spec.sheet)
)[0];
if (!spec
|| spec.column !== e.range.columnStart
|| spec.rowStart > e.range.rowStart) {
return;
}
const checkboxCell = sheet.getRange(e.range.rowStart, spec.checkboxColumn);
if (e.value) {
checkboxCell.insertCheckboxes();
} else {
checkboxCell.clearDataValidations();
checkboxCell.clearContent();
}
}
这是更新后的代码:
/**
* Simple trigger that runs each time the user hand edits the spreadsheet.
* Inserts and removes checkboxes depending on whether another column is blank.
*
* @param {Object} e The onEdit() event object.
*/
function onEdit(e) {
// version 1.1, written by --Hyde, 30 December 2022
// - see https://webapps.stackexchange.com/q/153531/269219
if (!e) throw new Error('Please do not run the onEdit(e) function in the script editor window.');
const specs = [
{ sheet: "Sheet1", column: 4, rowStart: 2, checkboxColumn: 1, },
];
console.log(specs);
let sheet;
const spec = specs.filter(spec =>
spec.column === e.range.columnStart
&& (sheet = e.range.getSheet()).getName().match(spec.sheet)
)[0];
if (!spec
|| spec.column !== e.range.columnStart
|| spec.rowStart > e.range.rowStart) {
return;
}
const checkboxCell = sheet.getRange(e.range.rowStart, spec.checkboxColumn);
if (e.value) {
checkboxCell.insertCheckboxes();
} else {
checkboxCell.clearDataValidations();
checkboxCell.clearContent();
}
}
我唯一改变的是
column
从 2
到 4
并且它按预期工作。
结果如下:
让我知道这是否适合您!