0
0

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] ライブラリの中からスプレッドシートを取得できるのか?→できる

0
Posted at

こんな事がありました

複数のスプレッドシートに、全く同じGASを適用させたい。
スプレッドシートごとにスクリプトエディタ入れて、コードをコピーして、、、ってやりたくない。
コードを「ライブラリ」にして、各スクリプトエディタから読み込むだけにしたい。

疑問点として「スタンドアロンであるライブラリから、Spreadsheet.getActive()ってできるんだっけ?」
の調査。

結果としては「できる」

スタンドアロンスクリプトからは当然無理

/**
 * ライブラリ(スタンドアロンスクリプト)の中のコード
 */
function getSsName(){
  const ss = SpreadsheetApp.getActive()
  console.log(ss.getName()) 
} 
実行結果
TypeError: Cannot read properties of null (reading 'getName')

そりゃそうですよね。スタンドアロンスクリプトなんだから SpreadsheetApp.getActive() できないですよね。

ライブラリにして読み込むとスプレッドシートを取得できる

上記のスクリプトを「ライブラリ」として公開する。(公開の仕方は調べてみてください)

下記は「そんなことできるのか?」という名前のスプレッドシートにバインドされているスクリプト。上のライブラリを LIB としている

スプレッドシートにバインドされてるスクリプト
/**
 * 「そんなことできるのか?」という名前のスプレッドシートにバインドしているスクリプト
 */
function myFunction() {
  LIB.getSsName()
}
実行結果
そんなことできるのか?

よかった。コード管理が楽になりそう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?