我正在为学区的学生会顾问制作一份谷歌电子表格,以填写。我试图这样做,当一个单元格被填写时,它不再可编辑。我发现以下代码可以防止在输入数据后编辑单元格。
function onEdit() {
var masterSheetName = "Master"
var helperSheetName = "Helper"
var firstDataRow = 1;
var firstDataColumn = 1;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var masterSheet = ss.getActiveSheet();
if (masterSheet.getName() != masterSheetName) return;
var masterCell = masterSheet.getActiveCell();
if (masterCell.getRow() < firstDataRow || masterCell.getColumn() < firstDataColumn) return;
var helperSheet = ss.getSheetByName(helperSheetName);
var helperCell = helperSheet.getRange(masterCell.getA1Notation());
var newValue = masterCell.getValue();
var oldValue = helperCell.getValue();
if (oldValue == "") {
helperCell.setValue(newValue);
} else {
masterCell.setValue(oldValue);
}
}
这很好用,但我需要延迟,以防万一有人搞砸输入信息,他们有时间修复它。 I tried using utilities.Sleep() 这样做,但似乎没有效果。如何延迟最终确定此信息,以便输入者有时间修复他们的回复?
答案 0 :(得分:1)
您可以添加另一张表来存储首次编辑单元格的时间。 试试这个
function onEdit() {
var masterSheetName = "Master"
var helperSheetName = "Helper"
var timeSheetName = "Time"
var firstDataRow = 1;
var firstDataColumn = 1;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var masterSheet = ss.getActiveSheet();
if (masterSheet.getName() != masterSheetName) return;
var masterCell = masterSheet.getActiveCell();
if (masterCell.getRow() < firstDataRow || masterCell.getColumn() < firstDataColumn) return;
var helperSheet = ss.getSheetByName(helperSheetName);
var timeSheet = ss.getSheetByName(timeSheetName);
var helperCell = helperSheet.getRange(masterCell.getA1Notation());
var timeCell = timeSheet.getRange(masterCell.getA1Notation());
var newValue = masterCell.getValue();
var oldValue = helperCell.getValue();
var time = timeCell.getValue();
if (oldValue == "" || time === "") {
helperCell.setValue(newValue);
timeCell.setValue(new Date());
} else if(Date.now() - time < 5000) {
helperCell.setValue(newValue);
} else {
masterCell.setValue(oldValue);
}
}
当然,您还应隐藏并保护帮助者和时间表,以便其他人无法编辑它们。
答案 1 :(得分:0)
获取一个全局变量(在函数外部)并设置当前日期时间,如果单元格为空(第一次访问)。我希望下面的代码有帮助。
var firstEntryTime = null;
function onEdit() {
var currentDateTime = new Date();
var masterSheetName = "Master"
var helperSheetName = "Helper"
var firstDataRow = 1;
var firstDataColumn = 1;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var masterSheet = ss.getActiveSheet();
if (masterSheet.getName() != masterSheetName) return;
var masterCell = masterSheet.getActiveCell();
if (masterCell.getRow() < firstDataRow || masterCell.getColumn() < firstDataColumn) return;
var helperSheet = ss.getSheetByName(helperSheetName);
var helperCell = helperSheet.getRange(masterCell.getA1Notation());
var newValue = masterCell.getValue();
var oldValue = helperCell.getValue();
if (oldValue == "") {
helperCell.setValue(newValue);
firstEntryTime = currentDateTime;
} else if (currentDateTime.getMinutes() >= firstEntryTime.getMinutes() + 5) {
masterCell.setValue(oldValue);
}
}