기본 콘텐츠로 건너뛰기

How to link schedules to Google Calendar with Google Spreadsheets

I tend to use Google products a lot. My main calendar is also Google Calendar. As I became an executive of the group this time, I had to register my members' birthdays on the calendar. While I was just registering one by one, "What am I doing right now?" I'm starting to feel that kind of shame.

The thought of registering the date information (birthday) on the Google sheet at once easily crossed my mind. So I looked it up and... I think it'll be possible if I write a little macro program.

So I worked hard to develop it.
It took 8 hours to register in an hour, so I made a program.
As a result, it was more inefficient. crying
But...
It was inefficient for me, but I think it could be of great help to others if I disclose this code, so I'm going to reveal the code.

Supplies

All you need is a Google spreadsheet and a Google calendar. Of course, it's free.

Google Calendar

First, create a Google Calendar or prepare the calendar you are using.

  1. ... on the right side of the calendar you want to apply.Click on
  2. Select Set up and share.

  1. Remember your calendar ID. We will use this ID later.

Google Spreadsheet

회원생일 스프래드시트 공유

Create lists and birthdays with Google Spreadsheets.

▲ You can fill it out as above, and the important thing is...

Date of birth must match the date format of the Google Sheet. And Gallinder registration, Calendar status must be required.

  • Register calendar : Indicates whether to register or remove from calendar (ADD/ DEL)
  • Calendar status : Check if the item is applied to the current calendar (Y/')

Creating a Macro Program

The basic preparations are done. From now on, you can create Apps Script and register the trigger.

Create Apps Script

Apps Script is a programming language designed to enable programming in javascript grammar for Google products. You can use this script to create macros in detail.

  1. Select Extension from the top menu of the calendar.
  2. Select Apps Script.

  1. First, create a random script name.
  2. Select Editor on the second of the five menus.
  3. You can use the default function or press + to create a new function.
  4. Change the name to create a specific name. (You can use the default function name.) Now you can write a program on this function and copy and apply the code I wrote.

Full code

/****************************************************************************************************
 * Ability to automatically register a member's birthday on a calendar
 ****************************************************************************************************/

function goBirthCreate() {
  /*****************************************************************************************************
   **************     User needs to register ************************************************************
   *****************************************************************************************************
   * SheetTabName: The name of the Sheettab at the bottom of the spreadsheet
   * Header~~: If you enter the header name of the spreadsheet, register the cell in Google Calendar
   * startRow : The starting point (row) of the table where the first data starts
   * startColumn : The starting point of the table where the first data starts (column
   * CalendarId : Found and created in the calendar you want to register
   * TitlePrefaceWord: Header that will be commonly used in the title part when registering on the calendar
   * descPrefaceWord : It is a delimited word that is commonly included in the content part when registering in the calendar (required because it is necessary to delete calendar events)
   * registerYear : year to register in calendar
   * alarm : Alarm (reminder) minutes to register with the calendar (number in minutes)
   *****************************************************************************************************/
  const SheetTabName = "회원생일";
  const HeaderTitle = "성명";
  const HeaderStartTime = "생년월일";
  const HeaderDescription = "";
  const HeaderEtc = "";
  const HeaderRegYN = "캘린더등록";
  const HeaderRegState = "캘린더상태";
  const startRow = 3;
  const startColumn = 2;
  const calendarId = "su***************************lendar.google.com";
  const titlePrefaceWord = "[Test Birthday]";
  const descPrefaceWord = "[Google Sheet_Birthday]";
  const registYear = "2022";
  const alarm1 = "10080"; // first alarm (number in minutes)
  const alarm2 = "500"; // second alarm (number in minutes)
  /****************************************************************************************************/
  /****************************************************************************************************/
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SheetTabName);
  const eventCal = CalendarApp.getCalendarById(calendarId);
  const endRow = spreadsheet.getLastRow();
  const endColumn = spreadsheet.getLastColumn();
  const count = spreadsheet.getRange(startRow, startColumn, endRow, endColumn).getValues(); // getRange(row, column, numRows, numColumns)

  ////////////////////////////////////////////////////////////////////////////////////////////////////
  const colHeaderStartTime = spreadsheet.createTextFinder(HeaderStartTime).findNext().getColumnIndex() - startColumn;
  const colHeaderTitle = HeaderTitle ? spreadsheet.createTextFinder(HeaderTitle).findNext().getColumnIndex() - startColumn : "";
const colHeaderDescription = HeaderDescription ? spreadsheet.createTextFinder(HeaderDescription).findNext().getColumnIndex() - startColumn : "";
  const colHeaderEtc = HeaderEtc ? spreadsheet.createTextFinder(HeaderEtc).findNext().getColumnIndex() - startColumn : "";
  const colHeaderRegYN = spreadsheet.createTextFinder(HeaderRegYN).findNext().getColumnIndex() - startColumn;
  const colHeaderRegState = spreadsheet.createTextFinder(HeaderRegState).findNext().getColumnIndex() - startColumn;
  /////////////////////////////////////////////////////////////////////////////////////////////////////

  for (x = 0; x < count.length; x++) {
    /**********************************************************************************************/
    if (x === 15) Utilities.sleep (2 * 1000); // Error registering many calendars at once
    /**********************************************************************************************/
    const shift = count[x];
    const regYes = shift[colHeaderRegYN];
    const title = shift[colHeaderTitle];
    const description = shift[colHeaderDescription] ? shift[colHeaderDescription] : "";
    const etc = shift[colHeaderEtc] ? "\n" + shift[colHeaderEtc] : "";
    const titleSum = titlePrefaceWord + " " + title;
    const descriptionSum = descPrefaceWord + " " + description + etc;
    /***********************************************************************************************/

    /***********************************************************************************************
     * StartTime is registered this year or next year, so the registration is processed by excluding the year from the birthday and replacing it with the designated year
     ***********************************************************************************************/
    // Start replacing EST time with KOR time
    const KR_TIME_DIFF = 9 * 60 * 60 * 1000;
    const startCurr = new Date(shift[colHeaderStartTime]);
    const startUtc = startCurr.getTime() + startCurr.getTimezoneOffset() * 60 * 1000;
    const startT = new Date(startUtc + KR_TIME_DIFF);
    // Replacement of EST time with KOR time is finished
    const startTimeMonth = startT.getMonth();
    const startTimeDay = startT.getDate();
    const startCalendarTime = new Date(registYear, startTimeMonth, startTimeDay);
    /***********************************************************************************************/

    if (regYes === "DEL" || regYes === "del" || regYes === "D") {
      const events = eventCal.getEventsForDay(startCalendarTime, { search: descPrefaceWord });
      for (y = 0; y < events.length; y++) {
        events[y].deleteEvent();
      }
      spreadsheet.getRange(Number(startRow + x), colHeaderRegYN + startColumn).setValue("");
      spreadsheet.getRange(Number(startRow + x), colHeaderRegState + startColumn).setValue("");
    } } else if (regYes === "ADD" || regYes === "add" || regYes === "A") {
      const event = {
        description: descriptionSum,
        guests: "",
      };
      if (titleSum !== null && titleSum !== "") {
        const events = eventCal.getEventsForDay(startCalendarTime, { search: descPrefaceWord });
        for (y = 0; y < events.length; y++) {
          events[y].deleteEvent();
        }
        eventCal.createAllDayEvent(titleSum, startCalendarTime, event).addPopupReminder(alarm1).addPopupReminder(alarm2);

        spreadsheet.getRange(Number(startRow + x), colHeaderRegYN + startColumn).setValue("");
        spreadsheet.getRange(Number(startRow + x), colHeaderRegState + startColumn).setValue("Y");
      }
    }
  }
}

function onOpenBirth() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu ("Calendar Sync").addItem ("Member Birthday Update", "goBirthCreate").addToUi();
}

Partial code

The code is largely composed of two functions.

function goBirthCreate() {}
function onOpenBirth() {}
  • goBirthCreate() : Code to apply birthday
  • onOpenBirth() : Code that makes the application button appear on the Google sheet

Code Settings Area

The top part is the setting part.

/*******************************************************************/

constSheetTabName = "회원생일"; // Name of Tab at the bottom of the spreadsheet
Const HeaderTitle = "성명"; // [Header Name in Table] What will be registered as the title of the calendar
constHeaderStartTime = "생년월일"; // Date to be registered in [Header Name in Table] calendar
ConstHeaderDescription = ""; // [Header Name in Table] What will be registered as the content of the calendar
Const HeaderEtc = ""; // [Header Name in Table] What will be registered with the contents of the calendar
const HeaderRegYN = "캘린더등록"; // [Header name in table] Set whether to register or delete in calendar (ADD/DEL)
Const HeaderRegState = "캘린더상태"; // [Header Name in Table] Indicates whether or not it is registered in the current calendar
const startRow = 3; // Line number from which the actual data starts
Const startColumn = 2; // The number of columns where the actual data starts
const calendarId = "sunrl******************************dar.google.com"; // calendar ID
constitlePrefaceWord = "[Test Birthday]"; // Horsehead to register in calendar title
constdescPrefaceWord = "[Google Sheet_Birthday]"; // Horsehead to register for calendar content
constregisterYear = "2022"; // Set the year to register in the calendar
const alarm1 = "10080"; // the first alarm to register with the calendar (number in minutes)
const alarm2 = "500"; // Second alarm to register with the calendar (number in minutes) calendar
/******************************************************************/

Register a trigger

Once the code has been registered and set up, you must now write and apply a trigger code so that it can be applied in certain situations.

Code for applying trigger

function onOpenBirth() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu("Calendar Sync").addItem("Member Birthday Update", "goBirthCreate").addItem("Member Birthday Update 2", "code").addToUi();
}

If you write the code as shown above, a button is created in the top menu as shown below. And when you click this button, the program runs and is reflected in the calendar.

If you attach .addItem(), the menu will continue to be added down.

  1. The calendar synchronization button is visible.
  2. I can see the member birthday update button.

Reflect triggers

You can now register a trigger that runs onOpenBirth() when a particular event occurs.

  1. Select the Trigger menu from the left.
  2. Click the Add Trigger button to generate a new trigger.
  3. Select the onOpenBirth we created as a function to run.
  4. Select Head.
  5. We will reflect the events that occur in the spreadsheet.
  6. When the spreadsheet is opened, it means that you want to run this function.
  7. Immediate notification if trigger fails. When you open the spreadsheet, you will automatically see the "Synchronize Calendar" button on the top menu. When adding or deleting birthdays, simply press the button to reflect them.

Test it out

If you run it, you'll see that it reflects well.

댓글

이 블로그의 인기 게시물

CSS에서 ellipsis('...')를 처리하는 방법

이번에 ellipsis에 대해 정리해 보도록 하겠습니다. 보통 게시판 리스트의 제목부분이 길어질 경우 php나 jsp등의 프로그램단에서 일정 글자수 이상이 되는 것에 대해 '...'으로 마무리 하는 경우가 많은데요.. 이것을 프로그램이 아닌 CSS만 가지고도 처리할 수 가 있습니다. 한줄라인 글자수 제한 한줄 라인 글자수 를 제한하는 방법은 아래와 같습니다. <div class="txt_line">통영의 신흥보물 강구안의 동쪽벼랑인 동피랑의 벽화마을을 다녀왔다</div> .txt_line { width:70px; padding:0 5px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } Block레벨 테그에서만 적용됨. overflow:hidden : 넓이가 70px를 넒어서는 내용에 대해서는 보이지 않게 처리함 text-overflow:ellipsis : 글자가 넓이 70px를 넘을 경우 생략부호를 표시함 white-space:nowrap : 공백문자가 있는 경우 줄바꿈하지 않고 한줄로 나오게 처리함 (\A로 줄바꿈가능) 멀티라인 글자수 제한 멀티라인에 대해서 글자수를 제한하는 방법은 아래와 같습니다. <p class="txt_post">통영의 신흥보물 강구안의 동쪽벼랑인 동피랑의 벽화마을을 다녀왔다.&nbsp; 비도 추적추적 내리고 일정상 늦으막해서 그런지 사람이 많지는 않았다. 덕분에 보통때는 한참을 기다려야 겨우 날개달린 사진을 찍을 수 있었을 텐데, 이번에는 바로 천사날개를 달고 사진을 찍을 수 있는 행운까지 얻었다. 이번이 동피랑 벽화마을 방문 3번째인데 예전에 왔을때에 비해서 벽화가 많이 바뀌어 있었다</p> .txt_post { overflow: hidden; text-ove...

Google 스프레드시트로 구글캘린더에 일정 연동하는 방법

저는 구글 제품을 많이 사용하는 편입니다. 제 주력 캘린더도 Google 캘린더 고요. 이번에 모임의 임원을 맡게 되면서 회원들의 생일을 캘린더에 등록해야 할 일이 생겼어요. 그냥 하나하나 등록을 하는 도중 "내가 지금 뭐하고 있나.." 라는 자괴감이 들기 시작했어요. 구글 시트에 있는 날짜 정보(생일)을 한 번에 쉽게 일괄 등록할 수는 없을까라는 생각이 뇌리를 스쳤습니다. 그래서 찾아봤더니.. 약간의 매크로 프로그램을 작성하면 가능할 것 같더라고요. 그래서 열심히 개발을 해봤습니다. 1시간이면 등록할 것을 8시간 걸려서 프로그램을 짜 봤어요. 결과적으로는 더 비효율적이었네요. ㅠㅠ 그러나... 나에게는 비효율 적이었지만 이코드를 공개하면 다른 사람에게는 큰 도움이 될 수 있겠구나 생각을 하고 코드를 공개해 보려고 합니다. 준비물 준비물은 Google 스프레드시트, Google 캘린더만 있으면 돼요. 당연히 무료고요. Google 캘린더 먼저 Google 캘린더를 만들거나 사용하고 있는 캘린더를 준비합니다. 적용하기 원하는 캘린더의 우측의 ... 를 클릭하고 설정 및 공유 를 선택합니다. 캘린더 ID를 잘 기억해 놓습니다. 나중에 이 ID를 활용할 예정입니다. Google 스프레드시트 회원생일 스프래드시트 공유 Google 스프레드시트로 명단과 생일을 작성합니다. ▲ 위와 같이 작성을 하면 되고 중요한 사항은.. 생년월일 이 구글 시트의 날짜 형식에 맞아야 합니다. 그리고 갤린더등록 , 캘린더상태 의 항목은 필수로 있어야 합니다. 캘린더등록 : 캘린더에 등록할지 제거할지를 표시 (ADD / DEL) 캘린더상태 : 현재 캘린더에 해당 항목이 적용되었는지 확인 (Y / ' ') 매크로 프로그램 작성하기 기본적인 준비는 끝났습니다. 이제부터 Apps Script를 제작하고 트리거를 등록하면 됩니다. Apps Script 작성하기 Apps Script 는 구글 제품에 대...

Google캘린더(달력)에 대한민국 휴일 표시하기

구글 캘린더에 대한민국 휴일을 표시하는 설정에 대해서 소개합니다. 네이버 달력이라면 그냥 기본으로 나오겠지만 구글캘린더의 경우는 별도의 설정을 해 주어야 합니다. 휴일의 표시는 각 나라의 휴일을 구글에서 미리 작성해 놓은 것을 내 캘린더에 불러와 적용하는 방식으로 되어 있습니다. 대한민국 공유일 표시하기 먼저 설정화면으로 이동합니다. 캘린더 화면의 우측상단의 설정 아이콘을 클릭합니다. 메뉴 중 설정 을 클릭합니다. 설정화면 중 좌측 메뉴에서 캘린더 추가 메뉴를 선택합니다. 관심분야와 관련된 캘린더를 선택합니다. 지역 공휴일의 모두 둘러보기 를 선택하면 각나라의 휴일을 선택할 수 있습니다. 우리는 대한민국의 휴일 을 선택합니다. 캘린더에서 공휴일 보기 대한민국 휴일에 대한 설정을 했다면 이제 보기 좋게 표시하면 됩니다. 설정을 정상적으로 했다면 좌측메뉴에 대한민국의 휴일 이라는 캘린더가 보입니다. 캘린더명의 우측끝에 더보기 아이콘 을 선택합니다. 색상을 빨간색으로 선택합니다. (보통 공휴일은 빨간색이므로.. ㅎ) 그러면 캘린더에 휴일의 명칭이 빨간색 으로 표시되게 됩니다. 감사합니다.