google-apps-script - 使用脚本检测 Google 表格中的公式错误

标签 google-apps-script

我的最终目标是here ,但是因为我没有得到任何答复,所以我开始从头开始学习(无论如何可能是最好的)。基本上,我想要一个脚本来识别错误并修复它们

嗯,第一部分是能够识别错误。有没有办法使用 Google Script 来识别单元格中是否有错误,并因此返回特定消息?或者我是否只需要做一个 if/else 说“如果单元格值为‘#N/A’,则执行此操作”,加上“如果单元格值为‘#ERROR’,则执行此操作”,继续出现各种错误?.基本上我想要 ISERROR(),但在脚本中

最佳答案

使用一个辅助函数来抽象掉这些肮脏的东西:

function isError_(cell) {
  // Cell is a value, e.g. came from `range.getValue()` or is an element of an array from `range.getValues()`
  const errorValues = ["#N/A", "#REF", .... ];
  for (var i = 0; i < errorValues.length; ++i)
    if (cell == errorValues[i])
      return true;

  return false;
}

function foo() {
  const vals = SpreadsheetApp.getActive().getSheets()[0].getDataRange().getValues();
  for (var row = 0; row < vals.length; ++row) {
    for (var col = 0; col < vals[0].length; ++col) {
      if (isError_(vals[row][col])) {
        Logger.log("Array element (" + row + ", " + col + ") is an error value.");
      }
    }
  }
}

使用 Array#indexOf 在辅助函数中:
function isError_(cell) {
  // Cell is a value, e.g. came from `range.getValue()` or is an element of an array from `range.getValues()`
  // Note: indexOf uses strict equality when comparing cell to elements of errorValues, so make sure everything's a primitive...
  const errorValues = ["#N/A", "#REF", .... ];
  return (errorValues.indexOf(cell) !== -1);
}

如果/何时使用 Array#includes 升级 Google Apps 脚本,这将是比 Array#indexOf 更好的选择:
function isError_(cell) {
  // cell is a value, e.g. came from `range.getValue()` or is an element of an array from `range.getValues()`
  const errorValues = ["#N/A", "#REF", .... ];
  return errorValues.includes(cell);
}

现在 v8 运行时可用,可以对上述代码片段(箭头函数等)进行许多其他更改,但请注意,不需要以这种方式更改内容。

关于google-apps-script - 使用脚本检测 Google 表格中的公式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49161874/

相关文章:

javascript - 如何在 html 小程序中使用 Google 应用脚本属性服务

javascript - 如何通过邮件退回尸体? MailApp.sendEmail() 错误

javascript - 从一个单元格复制一个值并将其粘贴到另一个 - Google Apps 脚本

Javascript 一对一对象映射(内置函数?)

google-apps-script - Google Apps 脚本中的范围要求过高

google-apps-script - 用于复制和重命名电子表格的 Google Sheets 脚本

google-apps-script - 谷歌电子表格 : Set a default value to all the cells in a column with/with out script

javascript - "Attribute provided with no value"错误 - UrlFetchApp

google-apps-script - 用于触发单元格值更改的 Google App 脚本

sql - 谷歌 BigQuery : Error 413 Response is too large