Googleスプレッドシートで管理しているスケジュールが、GAS(Google Apps Script)を介して自動でGoogleカレンダーと同期されたら、かなり便利です。実際にそのようなご依頼は過去数度頂戴しております。
今回は、ちょっと無料公開レベルでは惜しいくらい、コピペで即戦力となるサンプルコードをご紹介いたします。
私が作成したサンプルコードの主な仕様は以下の通りです。
<サンプルコードの仕様>
・サンプルで使用するスプレッドシートの中身は後ほどご案内する画像の通りとなっています。
・"シートの名前"の部分を、実際のスケジュール管理シート名に置き換えてください。
・"カレンダーID"の部分を、同期されたいGoogleカレンダーのカレンダーIDに置き換えてください。
・スケジュール管理シート以外でのシート上での操作やヘッダー行(1行目)での操作時にはスクリプトは発動しません。
・「カレンダーイベントID」列には、カレンダーアイテム作成時に自動で値が挿入されます。
・「終了時間」列の値の入力・編集完了(=別のセルがアクティブになるタイミング)がトリガーとなりGoogleカレンダーと自動同期されます。
・スケジュール内容を更新されたい場合は、対象行の「終了時間」列の値を編集してください。
かなり痒いところにまで手が届いたサンプルコードになっていますが、カスタマイズすれば更に便利にご利用いただけるかと思いますので、ぜひ、ご自由にお使いください!
※ご質問にはお答えできませんので予めご承知おきくださいませ。
スプレッドシートイメージ

カレンダーアイテムイメージ

コード
function syncToCalendar() {
const sheetName = "シートの名前";
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const activeCell = sheet.getActiveCell();
const activeCol = activeCell.getColumn();
const activeRow = activeCell.getRow();
// 対象シートの操作でない場合、対象セル範囲でない場合は何もしない
if (sheet.getSheetName() !== sheetName || activeRow <= 1 || activeCol !== 6) {
return;
}
const calendar = CalendarApp.getCalendarById("カレンダーID");
const values = sheet.getRange(activeRow, 1, 1, 7).getValues()[0];
const title = values[0] + " / " + values[1];
const startDate = new Date(values[2]);
const startTime = new Date(values[3]);
const endDate = new Date(values[4]);
const endTime = new Date(values[5]);
if (isNaN(startDate.getTime()) || isNaN(startTime.getTime()) || isNaN(endDate.getTime()) || isNaN(endTime.getTime())) {
Browser.msgBox("日付又は時間の入力セルに不備があります。正しい形式でご入力ください。");
return;
}
startDate.setHours(startTime.getHours());
startDate.setMinutes(startTime.getMinutes());
endDate.setHours(endTime.getHours());
endDate.setMinutes(endTime.getMinutes());
const options = {
description: values[6],
};
updateEvent(calendar, title, startDate, endDate, options, activeRow, sheet);
}
function updateEvent(calendar, title, startDate, endDate, options, activeRow, sheet) {
const eventIdCell = sheet.getRange(activeRow, 8);
const eventId = eventIdCell.getValue();
if (eventId === "") {
// カレンダーアイテム新規作成
let event = calendar.createEvent(title, startDate, endDate, options);
eventIdCell.setValue(event.getId());
} else {
// カレンダーアイテム更新
let event = calendar.getEventById(eventId);
if (event) {
event.setTime(startDate, endDate);
event.setDescription(options.description);
event.setTitle(title);
}
}
}
トリガー設定
対象関数:syncToCalendar
イベントのソースを選択:[ スプレッドシートから ]
イベントの種類の選択:[ 編集時 ]