🌟
【GAS】私がよく使うコードまとめ
私が業務中によく使うコードをまとめています。
今までは無題の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();
スプレッドシートの値を取得
mapとreduceを使う方法
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();
return values.map((rowValues, index) => {
const item = headers.reduce((obj, header, i) => {
obj[header] = rowValues[i];
return obj;
}, {});
item.row = index + 2;
return item;
});
}
forEachを使う方法
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.row = index + 2;
headers.forEach((header, index) => {
item[header] = value[index];
});
items.push(item);
};
return items;
}
オブジェクトを配列に戻す
mapを使う方法
const keys = [];//取り出したいkeyを配列で用意
function createArray(items, keys) {
const dataRows = items.map(item =>
keys.map(key => item[key])
);
return [keys, ...dataRows];
}
forEachを使う方法
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();
スプレッドシート作成、シート挿入、シートコピー
// スプレッドシート作成(とID取得)
const ssId = SpreadsheetApp.create(ssName).getId();
const ss = SpreadsheetApp.openById(ssId);
// 新しいシートの挿入と名前変更(0なら一番左に挿入される)
const newSheet = ss.insertSheet(0).setName(sheetName);
// 別シートからコピーして先頭に挿入
const ss = SpreadsheetApp.openById(spreadsheetId);
const templateSheet = ss.getSheetByName(templateSheetName);
const newSheet = templateSheet.copyTo(ss).setName(newSheetName).activate();
ss.moveActiveSheet(0);
スプレッドシートのシート取得
//スプレッドシートのURL取得
const ssUrl = ss.getUrl();
//シートのID取得
const sheetId = ss.getActiveSheet().getSheetId();
//連結してurl作成
const url = ssUrl + '#gid=' + sheetId;
今日の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, 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, 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);//メール送信
カレンダーの予定抽出
//calendarサービスを追加して使用
const events = Calendar.Events.list(calendarId, {
eventTypes: 'default',
timeMin: startDate.toISOString(),
timeMax: endDate.toISOString(),
});
const eventsJson = JSON.parse(events).items;//jsonに整える
console.log('eventsJson', eventsJson);
ドライブの移動
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
//一意の配列(かぶりを削除)
let uniqueArray = items.map(item => item.name);
uniqueArray = [...new Set(uniqueArray)];
//文字列のソート
items.sort((a, b) => {
return String(a.name).localeCompare(String(b.name));
});
アプリ作成(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コードあるよ」という方がいれば、ぜひコメントお待ちしてます。
参考(よくお世話になっているサイト)
↑かなり真似させてもらっています。
↑調べると必ずトップにくる素晴らしいサイト。
↑メール送信(下書き)参考
↑ブラウザボックス関係参考。
Discussion