2
1

More than 3 years have passed since last update.

Google Spreadsheetでアクティブなシートが変更されたときにスクリプトを実行したい

Last updated at Posted at 2020-05-18

概要

この投稿では、Google Spreadsheetでアクティブなシートが変更されたときにスクリプトを実行するための方法について記載させていただきます。2020年4月22日にonSelectionChangeのシンプルトリガーが追加されました。 残念ながら、私の環境ではこれはすぐには使用できず、セルを選択してもトリガーが発火しない状態が続いていました。今日、これを確認したところ、動作することを確認しましたので、ここではタイトルのゴールを実現するためのサンプルスクリプトを紹介させていただきます。

デモ

20200518b-fig1.gif

使用方法

次のような流れで使用してください。

  1. Google Spreadsheetのコンテナ―バウンドスクリプトへ下記のスクリプトをコピーペーストしてください。

    function onOpen(e) {
      const prop = PropertiesService.getScriptProperties();
      const sheetName = e.range.getSheet().getSheetName();
      prop.setProperty("previousSheet", sheetName);
    }
    
    function onSelectionChange(e) {
      const prop = PropertiesService.getScriptProperties();
      const previousSheet = prop.getProperty("previousSheet");
      const range = e.range;
      const a1Notation = range.getA1Notation();
      const sheetName = range.getSheet().getSheetName();
      if (sheetName != previousSheet) {
        range.setValue(`Changed tab from ${previousSheet} to ${sheetName}. ${a1Notation}`);
    
        // When the tab is changed, this script is run.
    
      } else {
        range.setValue(a1Notation);
      }
      prop.setProperty("previousSheet", sheetName);
    }
    
  2. Google Spreadsheetを一度閉じて、再度開いてください。

    • これにより、onOpenが実行され、現在のシート名がPropertiesServiceへ保存されます。
    • 現状ではonSelectionChangeのイベントオブジェクトには、シートの移動前後、選択されるセルの前後の情報は含まれていないようでした。これについては、今後のアップデートに期待したいと思います。このような情報を取得するために、このサンプルではPropertiesServiceを使用しています。
  3. ここで、スプレッドシート上のセルをクリックすると、onSelectionChangeが実行されて選択したセルにa1Notationが入力されます。また、アクティブシートを移動すると、これに基づいてシートがどこからどこへ移動したのかの情報がセルに入力されます。

onSelectionChangeのイベントトリガーは、いろいろなところで活躍しそうです。

参考

2
1
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
2
1