6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【GAS】操作するスプレットシートを指定する方法

Last updated at Posted at 2021-07-02

Google Apps Script(GAS)でスプレッドシートを読み込む方法には3つの方法が用意されています。今回は各々のスプレッドシートの取得メソッドについて紹介したいと思います。

アクティブな(今開いている)スプレットシートを指定して取得する方法

今開いているアクティブなスプレットシートを読み込むために使うのが、SpreadsheetAppクラスのgetActiveSpreadsheetメソッドです。
getActiveSpreadsheet()の基本的なコードは以下の通りです。

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

getActiveSpreadsheetメソッドは、コンテナバインド型のGASスクリプト(GASファイルをスクリプトエディタから作成した場合)でのみ使用することが可能です。

そのため、GoogleドライブからGASファイルを作成するスタンドアロン型のGASスクリプトでは、getActiveSpreadsheet()メソッドは利用することができません。

アクティブではないスプレットシートを指定して取得する方法

GASにアクティブではない別のスプレットシートを指定したい場合は、getActiveScreadsheet()は使わずに別の記述方法を用います。

openById(id)
openByUrl(url)
これら2つの記述方法があるので、1つずつ説明していきます。

1. openById(id)

openbyId(id)は引数に指定したid(スプレッドシートキー)からスプレッドシートを読み込みます。
openById(id)の基本的なコードは以下の通りです。

var spreadsheet = SpreadsheetApp.openById(id);

スプレットシートキーとは、スプレッドシートのURLの/d/と/editに囲まれた部分です。
https://docs.google.com/spreadsheets/d/xxxxxxxxx/edit~~~

このxxxxxxxxxの部分がスプレッドシートキーで、世界中の人が利用しているGoogleスプレッドシートの中でユニーク(唯一)になっています。
openById(id)のidをxxxxxxxxxに変えると下記のようになります。

var spreadsheet = SpreadsheetApp.openById(“xxxxxxxxx”);

これでアクティブではないスプレッドシート、つまりスクリプトと直接紐付いていないスプレッドシートを指定して取得することが可能になります。
openbyIdメソッドはコンテナバインドでもスタンドアロンのどちらのスクリプトでも実行が可能です。

2. openByUrl(url)

openbyUrl(url)は引数に指定したurlからスプレッドシートを読み込みます。
openbyIdと同様にコンテナバインドでもスタンドアロンでも利用可能なメソッドになります。
openByUrl(url)の基本的なコードは以下の通りです。

var spreadsheet = SpreadsheetApp.openByUrl(url);

このurlは、https://から始まるスプレットシートのURLを引数にしてます。
https://docs.google.com/spreadsheets/d/xxxxxxxxx/edit~~~

idの場合はxxxxxxxxxでしたが、urlなのでhttps://から最後までとなります。openByUrl(url)のurlを書き換えると下記のようになります。

var spreadsheet = SpreadsheetApp.openByUrl(“https://docs.google.com/spreadsheets/d/xxxxxxxxx/edit~~~”);

openById(id)とopenByUlr(url)を使用する際に気をつけなければいけないのが「””(ダブルクオーテーション)」をつけることです。これを忘れるとエラーで処理が実行できなくなります。

まとめ

今回は、GASでスプレットシートを指定する3つの方法について紹介しました。

1.アクティブなワークブックを指定する(スクリプトエディタから作成した場合のみ可能)
2.スプレットシートのID(スプレッドシートキー)で指定する
3.スプレットシートのURLで指定する

個人的には複数のスプレッドシートを使うことを考慮して始めからopenById(id)を使用しています。urlだとidよりも引数の文字数が多いため、どうしてもスクリプトの可読性が下がってしまいますからね。getActiveSpreadsheet()はスプレッドシートを1つしか使わないときには便利ですので、用途によって使い分けてみてください。

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?