3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GAS(Google Apps Script)のサンプルコード20選

3
Posted at

🧑‍💻【保存版】Google Apps Script(GAS)サンプルコード20選|まとめて試して学べる!【超初心者向け】

はじめに

Google Apps Script(GAS)は、GoogleスプレッドシートやGmailなどと連携して、業務を自動化できる最強の無料クラウドプログラミング環境です。

でも、最初は「何をどう書けばいいの?」と迷いがち…

そこで本記事では、GASをこれから学びたい超初心者向けに、実行できるサンプルコード20選をまとめました。

すべてコメント付きでわかりやすく、このままコピペすればすぐに使えるようになっています


✅ 使い方(超簡単3ステップ)

  1. Googleスプレッドシートを新規作成
  2. メニュー → 拡張機能 → Apps Script を開く
  3. 本記事のコードをコピペして保存
  4. ▶ボタンの横から関数名を選び、実行!

📦 一括インポート用:GASサンプルコード20選(コメント付き)

// --- 初級編 ---
// A1セルに「こんにちは、GAS!」と書き込む
function writeHello() {
  SpreadsheetApp.getActiveSheet().getRange("A1").setValue("こんにちは、GAS!");
}

// A1〜A5セルに「行◯です」と書き込む
function writeMultiple() {
  const sheet = SpreadsheetApp.getActiveSheet();
  for (let i = 1; i <= 5; i++) {
    sheet.getRange(i, 1).setValue(`行 ${i} です`);
  }
}

// ログにメッセージを出力する
function logMessage() {
  Logger.log("GAS練習中です!");
}

// 現在のシートの名前を変更する
function renameSheet() {
  SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet("練習シート");
}

// --- メール ---
// 自分宛にメールを送信(メールアドレスを書き換えて使ってください)
function sendMail() {
  MailApp.sendEmail("youremail@example.com", "GASからのメール", "これは自動送信です!");
}

// A1セルの内容をメール本文にして送信
function mailFromSheet() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const name = sheet.getRange("A1").getValue();
  MailApp.sendEmail("youremail@example.com", "通知", `A1セルの値は:${name}`);
}

// --- スプレッドシート操作 ---
// 全データをクリア
function clearSheet() {
  SpreadsheetApp.getActiveSheet().clear();
}

// 行数・列数をログに出力
function getSheetSize() {
  const sheet = SpreadsheetApp.getActiveSheet();
  Logger.log(`行数: ${sheet.getLastRow()} 列数: ${sheet.getLastColumn()}`);
}

// シートを複製して新しい名前を付ける
function duplicateSheet() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.copyTo(SpreadsheetApp.getActiveSpreadsheet()).setName("コピー_" + new Date().getTime());
}

// B1セルに現在の日付を入力
function writeToday() {
  SpreadsheetApp.getActiveSheet().getRange("B1").setValue(new Date());
}

// --- 日付処理 ---
// 1週間後の日付をログ出力
function futureDate() {
  const date = new Date();
  date.setDate(date.getDate() + 7);
  Logger.log(date);
}

// --- トリガー設定 ---
// writeHello() を毎日朝8時に自動実行するトリガーを作成
function createTrigger() {
  ScriptApp.newTrigger("writeHello")
    .timeBased()
    .everyDays(1)
    .atHour(8)
    .create();
}

// --- フォーム連携 ---
// Googleフォームを自動作成
function createForm() {
  const form = FormApp.create("アンケート");
  form.addTextItem().setTitle("お名前");
  form.addMultipleChoiceItem().setTitle("性別").setChoiceValues(["男性", "女性", "その他"]);
}

// --- 外部リクエスト ---
// GoogleトップページのHTMLを取得してログに出力
function getRequest() {
  const response = UrlFetchApp.fetch("https://www.google.com");
  Logger.log(response.getContentText().slice(0, 100));
}

// --- Googleドライブ連携 ---
// 新しいフォルダを作成
function createFolder() {
  DriveApp.createFolder("GASで作成されたフォルダ");
}

// ドライブ内のすべてのファイル名をログに出力
function listFiles() {
  const files = DriveApp.getFiles();
  while (files.hasNext()) {
    Logger.log(files.next().getName());
  }
}

// --- 応用操作 ---
// A1とB1セルの値を入れ替える
function swapCells() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const a = sheet.getRange("A1").getValue();
  const b = sheet.getRange("B1").getValue();
  sheet.getRange("A1").setValue(b);
  sheet.getRange("B1").setValue(a);
}

// A列の重複値を削除してユニークな値だけ残す
function removeDuplicates() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const data = sheet.getRange("A1:A" + sheet.getLastRow()).getValues();
  const unique = [...new Set(data.flat())];
  sheet.getRange(1, 1, sheet.getLastRow()).clear();
  unique.forEach((v, i) => sheet.getRange(i + 1, 1).setValue(v));
}

// B列のセルが「未完了」なら赤く塗る
function highlightIncomplete() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const rows = sheet.getLastRow();
  for (let i = 1; i <= rows; i++) {
    const status = sheet.getRange(i, 2).getValue();
    if (status === "未完了") {
      sheet.getRange(i, 2).setBackground("red");
    }
  }
}

// C1〜C10にチェックボックスを挿入
function insertCheckboxes() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange("C1:C10").insertCheckboxes();
}

📘 まとめ

  • GASはインストール不要・ブラウザだけで使えるプログラミング環境
  • 上記のコードを一括コピペするだけで、20個の関数を一気に試せます
  • スプレッドシートやGmailの自動化にすぐ使える内容ばかり!

✍️ コメント・LGTM歓迎!

「実行できた!」「こんな応用も知りたい!」という方は、コメント欄でぜひ教えてください。
応用編や演習形式も作成可能です!


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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?