简体   繁体   English

如何创建可以在Google应用脚本中终止的错误功能

[英]How to create an error function that can terminate in Google app script

In Google Sheets, I'm trying to create a checking function with Google Apps Script to ensure that certain cells are correctly filled up, and only if they're correctly filled up will the rest of the script run to update a separate table. 在Google表格中,我尝试使用Google Apps脚本创建检查功能,以确保某些单元格正确填充,并且只有在正确填充它们的情况下,其余脚本才会运行以更新单独的表。 In the code I've written, the updater function calls the checking function. 在我编写的代码中,更新程序功能调用了检查功能。 The checking function correctly throws up an alert when the error is detected, but after the alert is closed, it returns to the updater function to wrongly run the update. 当检测到错误时,检查功能会正确引发警报,但是在关闭警报后,它将返回到更新程序功能以错误地运行更新。 What I'd like is for the code to just stop after the error alert is acknowledged. 我想要的是代码在确认错误警报后才停止。 What am I doing wrong? 我究竟做错了什么?

My code (vastly simplified; I actually check for many errors): 我的代码(大大简化了;我实际上检查了很多错误):

function updater() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('update');
  var lower = sheet.getRange(1, 1).getValue;
  var higher = sheet.getRange(2, 1).getValue;
  verify(lower, higher) //check that values are correctly input
  /* run below only if no errors */
  sheet.getRange(5, 1).setValue(lower);
  sheet.getRange(5, 2).setValue((lower + higher) / 2);
  sheet.getRange(5, 3).setValue(higher);
}

function verify(inLow, inHigh) {
  var ui = SpreadsheetApp.getUI();
  var err = 'X';
  if (inLow > inHigh) {
    err = 'Bottom value should be lower than Top value. Please re-enter.';
  }
  if(err == 'X') {
    return; //if there are no errors, return to updater()
  } else {
    ui.alert(err); //if there's an error, show an alert. want it to end here
  }
}

You can make your verify function return a boolean value that you can use in an if condition. 您可以使您的verify函数返回一个布尔值,您可以在if条件中使用它。

modified code below : 修改后的代码如下:

function updater() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('update');
  var lower = sheet.getRange(1, 1).getValue;
  var higher = sheet.getRange(2, 1).getValue;
  if(verify(lower, higher)){ //check that values are correctly input
  /* run below only if no errors */
  sheet.getRange(5, 1).setValue(lower);
  sheet.getRange(5, 2).setValue((lower + higher) / 2);
  sheet.getRange(5, 3).setValue(higher);
  }
}

function verify(inLow, inHigh) {
  var ui = SpreadsheetApp.getUI();
  var err = 'X';
  if (inLow > inHigh) {
    err = 'Bottom value should be lower than Top value. Please re-enter.';
  }
  if(err == 'X') {
    return true; //if there are no errors, return to updater()
  } else {
    ui.alert(err); //if there's an error, show an alert. want it to end here
    return false;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM