GAS スプレッドシートのワークブックを選択する

GAS スプレッドシートのワークブックを選択する

GAS(Google Apps Script)で、スプレッドシートのワークブックを選択する手順を記述してます。対象のワークブックの「id」や「URL」から選択することができます。存在しない「id」や「URL」を指定するとエラーとなります。

環境

  • OS windows11 home
  • ブラウザ chrome 107.0.5304.88

ワークブックを選択

ワークブックを選択するには、まずは「スプレッドシートキー」という「スプレッドシート」のURLを指定する方法があります。

SpreadsheetApp.openById(id);

「id」はスプレッドシートの「URL」の「/d/と/edit」の間にあります。

実際に、使用してセル「A1」の値を変更してみます。

function myFunction() {

  // xxxxxには取得したIDを使用します
  var sg = SpreadsheetApp.openById('xxxxxxxxxxxxxxxx');

  sg.getCurrentCell().setValue('A1');  

}

実行結果

存在しないidを指定するとエラーが発生します。

function myFunction() {

  // xxxxxには取得したIDを使用します
  var sg = SpreadsheetApp.openById('xxxxxxxxxxxxxxxx');
  // Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.

  sg.getCurrentCell().setValue('A1');  

}

URLで指定

「スプレッドシート」のURLを指定する方法もあります。

SpreadsheetApp.openByUrl(URL);