首页 > 解决方案 > 更改单元格选择时显示警报弹出窗口 (onSelectionChange)

问题描述

我正在尝试使用新触发器在单元格选择更改时显示警报弹出窗口onSelectionChange。由于某种原因,它没有显示任何警报。我做错了什么或警报不适用于此触发器?

function onSelectionChange(e) {
      showAlert();
}
function showAlert() {
  var ui = SpreadsheetApp.getUi();
  var result = ui.alert(
                  'ALERT!',
                  'ALERT MESSAGE.',
               ui.ButtonSet.OK);
}

我也试过这样:

function onSelectionChange(e) {
  var ui = SpreadsheetApp.getUi();
  var result = ui.alert(
                  'ALERT!',
                  'ALERT MESSAGE.',
               ui.ButtonSet.OK);
}

标签: google-apps-scriptgoogle-sheets

解决方案


我创建了一个脚本来测试在 Google Apps 脚本中显示“弹出窗口”的不同方式。在这两种运行时中,只有使用 HTML 服务的运行时会引发错误。测试是使用 Chrome 完成的,这是一个 G Suite 帐户,只登录了一个帐户。

以下是引用脚本的代码:

function onSelectionChange(e) {
  var message = e.range.getA1Notation();
  switch(e.range.columnStart){
    case 1:
      alert(message);
      break;
    case 2:
      toast(message);
      break;
    case 3:
      msgBox(message);
      break;
    case 4:
      dialog(message);
      break;
    case 5:
      alertWithButton(message);
      break;
    default:
    console.info(message);
  }
}

function alert(message){
  SpreadsheetApp.getUi().alert(message);
}

function toast(message){
  SpreadsheetApp.getActiveSpreadsheet().toast(message);
}

function msgBox(message){
  Browser.msgBox(message);
}

function dialog(message){
  SpreadsheetApp.getUi().showModalDialog(
    HtmlService.createHtmlOutput(message), 
  'Alert'
  )
}

function alertWithButton(message){
  var ui = SpreadsheetApp.getUi();
  ui.alert(message, ui.ButtonSet.OK);
}

推荐阅读