目的是能够通过选中复选框来执行一些代码。
Checked
直观地告诉您该过程已经执行。如果取消选中,您会收到这样做的后果警告。
选中复选框会创建保护
protection.setWarningOnly(true)
,但取消选中 protection.remove()
不会删除此保护,如 AppsScript 代码中编程的那样。
我用最少的代码将问题减少到最小的工作表。 该工作表只是一个带有复选框的单元格(示例中的“A1”)。 (您可以添加更多...) 和一个触发器“OnEdit”来保护Cells(e)。
function protectCell(e) {
var sheet = e.source.getActiveSheet();
var eRange = e.range;
var protection = eRange.protect();
var isChecked = eRange.getValue();
//Browser.msgBox("Checkbox state: " + isChecked);
if (isChecked) {
// Lock the cell when the checkbox is checked
protection.setWarningOnly(true);
//Browser.msgBox("Protection set with warning.");
} else {
// Unlock the cell when the checkbox is unchecked
protection.remove();
//Browser.msgBox("Protection removed.");
}
}
您可以在 : 1
进行测试重复保护
如文档中所写,调用range.protect()
会重复保护:
如果该范围已受保护,此方法会创建一个与现有范围重叠的新受保护范围。因此,仅在删除所有现有保护后才调用
.protect()
。
/**
* @param {GoogleAppsScript.Events.SheetsOnEdit} e
*/
function protectCell(e) {
const ss = e.source;
const sheet = ss.getActiveSheet();
const eRange = e.range;
const thisProtectionDescription = 'protectedByScript1689';
const isChecked = eRange.isChecked();
if (sheet.getName() !== 'Sheet1') return;
//Remove all existing RANGE protections with description=protectionDescription
ss.getProtections(SpreadsheetApp.ProtectionType.RANGE).forEach(
(protection) => {
if (protection.getDescription() === thisProtectionDescription)
protection.remove();
}
);
if (isChecked && eRange.getA1Notation() === 'A1') {
// Lock the cell when the checkbox is checked
const protection = eRange.protect();
protection.setDescription(thisProtectionDescription);
protection.setWarningOnly(true);
//Browser.msgBox("Protection set with warning.");
}
}