Search code examples
google-sheetsgoogle-apps-script-editor

Stopping a script while running though dialogs


I am using a script to save data and clear the fields afterwards. Because the fields are being cleared, I want the user to verify (through a popup) that he really wants to do this operation. I have tried to use an alert with ok_cancel buttons, but when you cancel, the script continues.

The code that gets the user response:

var ui = SpreadsheetApp.getUi();
var result = ui.alert('Please confirm', 'Are you sure you want to save and clear?',
  ui.ButtonSet.OK_CANCEL);
if (result == ui.Button.OK)
  ui.alert('Data opgeslagen.');
else if (result == ui.Button.CANCEL)
  return;

/* Delete values here */

Solution

  • You have the delete in the wrong place. Try like this:

    function myFunction() {
    var ui = SpreadsheetApp.getUi();
    var result = ui.alert('Please confirm', 'Are you sure you want to save and clear?',
      ui.ButtonSet.OK_CANCEL);
      if (result == ui.Button.OK){
        ui.alert('Data opgeslagen.');
        var s=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
        s.clearContents()}
    else if (result == ui.Button.CANCEL)
    return;
    }