有没有人知道是否有办法访问编辑事件对象的旧(即编辑前)公式,而不是oldValue?我认为e.oldFormula可以工作,但它是未定义的,甚至在文档中都没有。
我正在编写一个脚本,在编辑某些范围时需要密码,但是,如果用户无法提供正确的密码,为了撤消编辑,我需要知道之前单元格中的内容。对于包含数字或字符串的单元格,e.oldValue效果很好,但我想要保护的大多数单元格都包含公式(这就是我想要保护它们的原因)所以e.oldValue会阻止数据更新,就像它应该的那样。
这是我得到的代码只有在单元格不包含公式时才有效(除此之外,它的效果很好:
// Prompt for password before allowing edit of formula cells
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var editRange = e.range;
var editCol = editRange.getColumn();
if (editCol != 4 ) {
var password = "321"; // not actual password
var passwordAttempt = Browser.inputBox('Enter Password to edit protected range, or hit cancel to cancel edit:', Browser.Buttons.OK_CANCEL);
if(passwordAttempt == password) {
Browser.msgBox('Edit Accepted');
} else {
if (passwordAttempt != 'cancel'){
Browser.msgBox('Incorrect password. Contact James Atkins for password to edit protected ranges.');
}
if(e.oldValue){
Browser.msgBox('old value is defined as ' + e.oldFormula);
e.range.setValue(e.oldValue);
} else {
e.range.clear();
}
}
仅供参考,我这样做是因为Google表格中的内置受保护范围不区分用户通过手动编辑更改单元格内容以及激活更改内容的脚本。我想允许所有用户激活排序和清除某些范围的脚本,但不要让他们手动弄乱内容。
答案 0 :(得分:0)
您可以通过创建工作表的克隆来跟踪公式,从而解决此问题。使克隆表不受最终用户的限制。所以他们无法编辑它。
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cloneSheet = ss.getSheetByName("cloneSheet")
var cell = sheet.getActiveCell();
var editRange = e.range;
var cloneRange = cloneSheet.getRange(editRange.getA1Notation())
var editCol = editRange.getColumn();
if (editCol != 4 && sheet.getName() != "cloneSheet") {
var password = "321"; // not actual password
var passwordAttempt = Browser.inputBox('Enter Password to edit protected range, or hit cancel to cancel edit:', Browser.Buttons.OK_CANCEL);
if(passwordAttempt == password) {
Browser.msgBox('Edit Accepted');
cloneRange.setValue(editRange.getFormula()) //modify the clone to match the new formula.
} else {
if (passwordAttempt != 'cancel'){
Browser.msgBox('Incorrect password. Contact James Atkins for password to edit protected ranges.');
}
if(e.oldValue){
Browser.msgBox('old value is defined as ' + cloneRange.getFormula());
e.range.setValue(cloneRange.getFormula());
} else {
e.range.clear();
}
}
}
}
但是,最终用户仍然可以看到密码。如果你真的是最终用户只做有限的改变,下面的解决方案会更好。
替代解决方案
当最终用户执行脚本时,即使您编写了脚本,它也会以最终用户的范围/标识运行。因此,如果他们没有编辑权限,那么在他们的别名下运行的脚本也没有。这是对您的评论的回应:
google sheet不区分用户通过手动编辑更改单元格内容以及激活更改内容的脚本来区分。
因此,如何解决此问题,您可以使用谷歌网络应用程序来运行排序和清除脚本。最终用户使用脚本使用UrlFetch调用此脚本,这解决了范围问题并阻止他们查看您的代码/密码等。
这是解决类似问题的问题: Google Apps Script: Temporarily run script as another user