google-apps-script - 当用户删除单元格内容时,如何获取单元格的oldValue?在这种情况下,e.oldValue 未定义

标签 google-apps-script google-sheets

当用户删除内容时,如何获取单元格的 oldValue?

这样做的目的是防止新手用户使用共享电子表格时意外删除/编辑。仅应更新空单元格而不发出警告。

它在编辑单元格内容时起作用。 但是当删除单元格内容时,oldValue 未定义 - 单元格有内容。

PS。我知道这仅适用于单个单元格编辑 - 我检查了范围宽度/高度 == 1,但对于值删除也不是这样。 (选择单元格,按删除)

我的测试代码如下:

function onEdit(e) {
  Logger.log("onEdit called") 
  Logger.log("e.oldValue: %s", e.oldValue) 
  Logger.log("e.value: %s", e.value)
  Logger.log(e) 
  if (!("value" in e) || (e.oldValue != undefined)) {
     if (shouldRevertChange(e.oldValue, e.range.getValue())) {
        e.range.setValue(e.oldValue);
     }
   }
}

function shouldRevertChange(oldValue, newValue) {
  var ui = SpreadsheetApp.getUi();

  var result = ui.alert(
     'Was this a mistake?',
    'You changed the contents of a cell. Old value: '+oldValue+', new value: '+newValue+'. Do you want to revert the change?',
      ui.ButtonSet.YES_NO);

  // Process the user's response.
  if (result == ui.Button.YES) {
    // User clicked "Yes".
    return true;
  } else {
    // User clicked "No" or X in the title bar.
    return false;
  }
}

这是我的测试表 - 可编辑: https://docs.google.com/spreadsheets/d/1BP0Zqbf8QndhI62AucT3nGNm9eUlgzxf0lTCy2UHe-0/edit?usp=sharing

同时测试脚本: https://script.google.com/d/1IuTpeEDlsqjDyp3ADRy2JYKzDymR7zOpPkamIcEUHnHXUNdA0SRf7xyU/edit?usp=sharing

我需要在警报消息中查看已删除单元格的旧值。

编辑值的消息: User alert 编辑值的日志: enter image description here

删除/清除值的消息: enter image description here

删除/清除值的日志(旧单元格值不存在): enter image description here

最佳答案

有一个插件可以为您完成此任务。它采用创建反射(reflect)真实电子表格的隐藏电子表格的方式。

https://gist.github.com/tanaikech/73edaed1268a6d07118aed538aa5608d

关于google-apps-script - 当用户删除单元格内容时,如何获取单元格的oldValue?在这种情况下,e.oldValue 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53475708/

相关文章:

google-apps-script - Google Apps脚本,使用格式将一个电子表格复制到另一电子表格

google-apps-script - Google 脚本搜索并返回单元格位置

google-apps-script - 为什么函数即使没有被调用也会运行?

google-sheets - 在 Google 表格中提取 '-' 字符后的子字符串

javascript - 运行 google apps 脚本 (UrlFetchApp) 时出现 "Window not defined"错误

javascript - 忽略其中包含公式的空单元格值

javascript - 如何根据其他变量设置一个变量

javascript - 在 Google Apps 脚本中返回具有合并列的某些行的范围

json - 将 JSON 数据作为表格导入到 google 表格中

一个单元格内多行的正则提取