LoginSignup
1
1

More than 1 year has passed since last update.

40 代おっさん GASのSpreadsheetAppクラスについて学ぶ

Posted at

本記事ついて

本記事は プログラミング初学者の私が学習していく中でわからない単語や概要をなるべくわかりやすい様にまとめたものです。
もし誤りなどありましたらコメントにてお知らせいただけるとありがたいです。

SpreadsheetAppクラス

SpreadsheetAppクラスとは
Spreadsheetサービスの最上位に位置するオブジェクト

メンバー 戻り値 説明
create(name) Spreadsheet 新しいスプレッドシートnameを作成する
flush() Void スプレッドシートの保留中の変更を適用する
getActiveRange() Range アクティブなセル範囲を収得する
getActiveSheet() Sheet アクティブなシートを収得する
getActiveSpreadSheet() Spreadsheet アクティブなスプレッドシートを収得する
getCurrenCell() Range 現在のセルを収得する
getUi() Ui スプレッドシートのUiオブジェクトを取得する
open(file) Spreadsheet ファイルfileをスプレッドシートとして取得する
openById(id) Spreadsheet 指定したidのスプレッドシートとして取得する
openByUrl(url) Spreadsheet 指定したurlのスプレッドシートとして取得する
setActiveRange(range) Range セル範囲rangeをアクティブにする
setActiveSheet(sheet) Sheet シートSheetをアクティブにする
setActiveSpreadsheet(newActiveSpreadsheet) void するnewActiveSpreadsheetをアクティブにする
setCurrentCell(cell) Range セルcellを現在のセルにする

スプレッドシートを取得する

スプレッドシートを収得する主な方法

・アクティブなスプレッドシートを取得する
・IDでスプレッドシートを取得する
・URLでスプレッドシートを取得する

アクティブなスプレッドシート

アクティブなスプレッドシートとは
スクリプトにバインドされているスプレッドシートを指す

構文

SpreadsheetApp.getActiveSpreadsheet()

アクティブなオブジェクトを取得するメソッドは、コンテナバインドスクリプトでのみ使用できる。

*コンテナバインド型は、スプレッドシートやドキュメント、フォームなどのGoogleのサービスに紐づく、Google Apps Scriptのスクリプトです。

バインドされていないスプレッドシートを収得sる場合は、別の方法が必要
その主な方法
IDにより収得する openByIdメソッド

構文

SpreadsheetAPP.openById(ID)

URLにより収得する openByUrlメソッド

構文

SpreadsheetApp.openByUrl(URL)

スプレッドシートはGoogleアプリケーションのアイテムは、URLが定められており、そのURLにアクセスすることでブラウザ上で開くことが出来る。
GASでも同様で、URLを知っているいれば、スクリプトから指定のスプレッドシートを収得できる。
IDはそのURLの一部を構成している。

https://docs.google.com/spreadsheets/d/{ID}/edit#gid=0

お試し

function toshiki4() {
  const ssActive = SpreadsheetApp.getActiveSpreadsheet();
  console.log(ssActive.getName());

  const url = 'https://docs.google.com/spreadsheets/d/××××××××/edit#gid=0'
  const ssByUrl = S×preadsheetApp.openByUrl(url);
  console.log(ssByUrl.getName());

  const id = '1OEin_rjSrOCukOhxJ5Lsu2SxRSVF8PHzc2MCu-cYG4o';
  const ssByid = SpreadsheetApp.openById(id);
  console.log(ssByid.getName());
}

*メソッド実行によるGoogleアプリケーションへのアクセスは実行時間が遅いという事実がある。
GASでは実行時間に関する厳しい制限がある。
Googleアプリケーションへアクセスをするメソッドの実行回数はできる限り減らすのが望ましい。

コンテナバインドスクリプトであれば、アクティブなシートを直接収得する方法としてgetActiveSheetメソッドを使うことができる。

構文

SpreadsheetApp.getActiveSheet()

お試し

function toshiki4() {
  const sheet = SpreadsheetApp.getActiveSheet();
  console.log(sheet.getName());
}

*複数のシートが存在している場合は、スクリプトから見て「どのシートがアクティブか」想定できないので注意
原則としてスプレッドシートが1つしかない場合、ブラウザでシートを開いている時のみ実行する。スクリプトの使用に限る。

参考資料

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