我有一列复选框:
.
如果选中一个框,它将为另一个工作表中的单元格设置一个值。
如果我选中 1 号框,它就会变为 true,而其余的仍然为 false
然后,如果我选中 2 号框,它也会随着 1 号框而变为 true,而其余的仍然为 false。这是正常操作,但我需要的是,当我选中一个框时,它会变为 true,而所有其他框都会变为 false,无论它们是否被选中。换句话说,我希望一次选中一个框。
我可以这样做吗?
这是我的代码,用于在选中该框时设置一个值:
var hasValue = sheet.getRange("B2:B").getValues();
for (var i = 0; i < hasValue.length; i++) {
if (hasValue[i][0] == true) {
var transfer = sheet2.getRange(2, 2, 1, 1).setValue(i + 1);
}
}
这种行为称为“单选按钮”。
实现它的最简单方法是绑定简单的编辑触发器:
- 检查编辑的范围以确定它是否位于您的复选框区域,如果不是则退出。
- 将所有复选框设置为 false
- 将编辑的单元格设置为事件对象中的适当值
- 如果需要,执行更新
您必须配置的极其简单的示例,并且仅配置用于单单元格编辑。
function onEdit(e) {
if (!e || e.value === undefined)
return; // The function was run from the Script Editor, or a multi-cell range was edited.
const edited = e.range;
const s = edited.getSheet();
if (s.getName() !== "some name")
return; // A cell on the wrong sheet was edited
if (isCheckboxRow_(edited.getRow()) && isCheckboxCol_(edited.getColumn())) {
// The cell edited was in a row and a column that contains a checkbox
updateCheckboxes_(s, edited, e);
}
}
function isCheckboxRow_(row) {
// Assumes checkboxes are only in rows 5, 6, 7, 8, 9, and 10
return row >= 5 && row <= 10;
}
function isCheckboxCol_(col) {
// Assumes checkboxes are in column A
return col === 1;
}
function updateCheckboxes_(sheet, editRange, eventObject) {
if (!sheet || !edit || !eventObject)
return; // Make sure all required arguments are defined (i.e. this was called and not run from the Script Editor)
const cbRange = sheet.getRange("A5:A10"); // location of the checkboxes in a radio group.
cbRange.setValue(false);
editRange.setValue(eventObject.value);
// Reference some other sheet
const targetSheet = eventObject.source.getSheetByName("some other sheet name")
if (!targetSheet)
return; // the sheet name didn't exist in the workbook we edited.
// Reference a cell in the same row as the cell we edited, in column 1
const targetCell = targetSheet.getRange(editRange.getRow(), 1);
if (eventObject.value) {
// when true, give the target cell the value of the cell next to the edited checkbox
targetCell.setValue(editRange.offset(0, 1).getValue());
// do other stuff that should be done when a checkbox is made true
} else {
// the checkbox was toggled to false, so clear the target cell
targetCell.clear();
// do other stuff that should be done when a checkbox is made false
}
}
上面暗示了一些建议的做法,例如使用辅助函数来封装和抽象逻辑,从而使函数更容易理解。
Review:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)