首页 > 解决方案 > try/catch 不适用于 google 脚本单元格验证错误

问题描述

我在具有验证的单元格中的脚本中有一个 setValue() 操作,如果我使用不在列表中的值,则会引发错误。没关系。但是我的问题是,当我尝试/捕获以避免错误时,它不起作用并且我一直收到相同的错误

重现问题:在 B2 值 a、b、c 列表中创建新工作表并设置验证,拒绝其他

function test() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  try { // don't work !!
    ss.getRange('B2').setValue('x'); // value not in validation list
  } catch(e) {Logger.log('error')}
}

问题出在哪里???

标签: google-apps-script

解决方案


您可以使用flush()set 之后的方法以到达 catch 部分。

function test() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  try { // don't work !!
    ss.getRange('B2').setValue('x'); // a text value not in validation list (with numeric values don´t fail)
    SpreadsheetApp.flush()
  } catch(e) {Logger.log('error')}
}

推荐阅读