LoginSignup
14
6

More than 1 year has passed since last update.

Google Apps Script で window.confirm のような挙動を実現する

Posted at

やりたいこと

JavaScript の window.confirm のように後続処理をユーザーが選択できるようにします。今回のケースでは選択したセルに UUID を入力するという処理を行いました。

apps-script-confirm.gif

概要

スプレッドシートと連携する Google Apps Script を作る際に、後続の処理を実行させるかどうか選択させたい場合があります。例えば請求書を作成するスクリプトで、既に請求書が作成済みの場合に 上書きする作業を中断する か、など一度実行した結果に対して再度処理をするかどうか選択するケースが多いと思います。

そのような場合に JavaScript でいう window.confirm のような機能が欲しくなります。

実現方法

Apps Script には Ui クラスが用意されており、これが使用できるケース(※)では以下のような記述で confirm メソッドを実装することができます。

const confirm = (message) => {
  const ui = SpreadsheetApp.getUi()
  return ui.alert(message, ui.ButtonSet.YES_NO) === ui.Button.YES
}

上記の関数は以下のように呼び出せます。

if (confirm('更新してもよろしいですか?')) {
  // 更新処理
}

※ 公式ドキュメントの通りコンテナバウンドされたケース(スプレッドシートや Docs, Slide, Form のファイルから Apps Script を作成するケース)に限られます。

A script can only interact with the UI for the current instance of an open editor, and only if the script is container-bound to the editor.

サンプルの全ソースコード

上記サンプルの全ソースコードを以下に記載しましたので、ご参考ください。

const onOpen = () => {
  SpreadsheetApp.getActiveSpreadsheet().addMenu('UUID', [
    { name: '生成', functionName: 'main' },
  ])
}

const main = () => {
  const cell = SpreadsheetApp.getActiveSheet().getActiveCell()
  const value = cell.getValue()
  if (!value || confirm('既に値が入力されています。上書きしますか?')) {
    cell.setValue(Utilities.getUuid())
  }
}

const confirm = (message) => {
  const ui = SpreadsheetApp.getUi()
  return ui.alert(message, ui.ButtonSet.YES_NO) === ui.Button.YES
}

以上!

14
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
6