🌟

【GAS】私がよく使うコードまとめ

2025/02/24に公開

私が業務中によく使うコードをまとめています。
今までは無題のApps scriptにまとめていたのですが

  • 転職したら見られなくなる
  • プライベートのPCから見られない
  • 増えてきて整理したい

といった理由から、改めて記事にしました(随時更新予定)。

スプレッドシート取得

const ss = SpreadsheetApp.getActiveSpreadsheet();//アクティブなスプレッドシートを取得
const ss = SpreadsheetApp.openById('スプレッドシートID');//idで取得
const sheet = ss.getSheetByName('シート1');//シートの取得

最終行、最終列の取得

const lastRow = sheet.getLastRow();
const lastRow = sheet.getRange(sheet.getMaxRows(), 1)
  .getNextDataCell(SpreadsheetApp.Direction.UP).getRow();

const lastCol = sheet.getLastColumn();
const lastCol = sheet.getRange(1, sheet.getMaxColumns())
  .getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn();

スプレッドシートの値を取得

function myfunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('シート1');
  const items = getItems(sheet);
}

function getItems(sheet) {
  const values = sheet.getDataRange().getValues();
  const headers = values.shift();
  const items = [];

  for (const [index, value] of values.entries()) {
    const item = {};
    item['行数'] = index + 2;
    headers.forEach((header, index) => {
      item[header] = value[index];
    });
    items.push(item);
  };

  return items;
}

オブジェクトを配列に戻す

const keys = [];//取り出したいkeyを配列で用意
function createArray(items, keys) {
  const array = [keys];
  items.forEach(item => {
    let elements = keys.map(key => item[key]);
    array.push(elements);
  });

  return array
}

目的の行列の番号検索

const targetRow = sheet.getRange('A:A').createTextFinder('keyword')
  .matchEntireCell(true).findNext().getRow();

const targetCol = sheet.getRange('1:1').createTextFinder('keyword')
  .matchEntireCell(true).findNext().getColumn();

今日の00:00

const now = new Date();
const y = now.getFullYear();
const m = now.getMonth();
const d = now.getDate();
const today = new Date(y, m, d, 0, 0, 0);

日付、時間の日本語変換

const DAY_OF_WEEK = ['日', '月', '火', '水', '木', '金', '土'];

//日付を日本語表記にする
function writeJPNDate(date) {
  const jpnDate = Utilities.formatDate(date, 'JST', 'yyyy年M月d日');

  return `${jpnDate}${DAY_OF_WEEK[date.getDay()]}`;
}

//時間を日本語表記にする
function writeJPNTime(time) {
  return Utilities.formatDate(time, 'JST', 'HH:mm');
}

営業日なら作動

function checkWorkingDate() {
  //今日の00:00作成
  const now = new Date();
  const y = now.getFullYear();
  const m = now.getMonth();
  const d = now.getDate();
  const today = new Date(y, m, d, 0, 0, 0);

  //日本の祝日のみのカレンダーを取得
  const jpHolidayCalendarId = 'ja.japanese.official#holiday@group.v.calendar.google.com';
  const jaHolidayCalendar = CalendarApp.getCalendarById(jpHolidayCalendarId);
  const events = jaHolidayCalendar.getEventsForDay(today);

  //土日の場合falseを返す
  if (time.getDay() === 0 || time.getDay() === 6) return false;

  //日本の祝日の場合falseを返す
  if (events.length > 0) return false;

  //営業日の場合trueを返す
  return true;
}

メール送信(下書き作成)

let recipients = '';
let subject = '';
let body = '';
let options = {
  cc: '',
  bcc: '',
  noReply: true,
  htmlBody: body
};

GmailApp.createDraft(recipients.join(','), subject, body, options);//下書き作成
GmailApp.sendEmail(recipients.join(','), subject, body, options);//メール送信

ドライブの移動

const DRIVE_ID = 'XXXXX';
const FILE_ID = 'YYYYY';
const driveFolder = DriveApp.getFolderById(DRIVE_ID);
const file = DriveApp.getFileById(FILE_ID);
file.moveTo(driveFolder);

ランダムID生成

function generateId() {
  const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  const lowercase = 'abcdefghijklmnopqrstuvwxyz';
  const numbers = '0123456789';
  const string = uppercase + lowercase + numbers;

  let id = '';
  for (let i = 0; i < 10; i++) {
    id += string.charAt(Math.floor(Math.random() * string.length));
  }

  return id;
}

ブラウザボックス

//メッセージボックス
const res = Browser.msgBox('title', 'prompt', Browser.Buttons.OK_CANCEL);
if (res === 'cancel') return;

//インプットボックス
const res = Browser.inputBox('title', 'prompt', Browser.Buttons.OK_CANCEL);
if (res === 'cancel') return;

ツールバー作成

function onOpen() {
  let ui = SpreadsheetApp.getUi();
  ui.createMenu('GAS実行')
  .addItem('テストタブ', 'XXXXX')
  .addToUi();
}

Tipsコード

//GAS実行者アドレス取得
const userAddress = Session.getActiveUser().getEmail();

//プロパティサービス利用
const properties = PropertiesService.getScriptProperties().getProperties();
const value = properties.key

アプリ作成(Bootstrap)

doget
function doGet() {
  let template = HtmlService.createTemplateFromFile('template/index');
  template.deployURL = ScriptApp.getService().getUrl();

  const htmlOutput = template.evaluate();

  //スマホ対応用のタグ
  htmlOutput.addMetaTag('viewport', 'width=device-width, initial-scale=1');
  return htmlOutput;
}
html
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
  <?!= HtmlService.createHtmlOutputFromFile('css').getContent(); ?>
</head>

<body>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous">
  </script>
</body>

</html>

おわりに

自分用ではあるのですが「役に立ったよ!!」とか「こんな便利なGASコードあるよ」という方がいれば、ぜひコメントお待ちしてます。

参考(よくお世話になっているサイト)

https://uncle-gas.com/
↑かなり真似させてもらっています。

https://tonari-it.com/
↑調べると必ずトップにくる素晴らしいサイト。

https://jp.tdsynnex.com/blog/google/options-sending-email-by-gas/
↑メール送信(下書き)参考

https://tatsuya-note.com/how-to-get-data-using-msgbox-in-gas/
↑ブラウザボックス関係参考。

Discussion