[GAS Beginner Series #76] Get Specific Google Calendars: How to Use CalendarApp.getCalendarById()

Starting with this article, we are finally diving into an exciting new phase: “Phase 8: Google Calendar Integration (#76 to #80)”!

Once you master automating Google Calendar with Google Apps Script (GAS), you can streamline tasks and achieve major productivity wins like these:

  • Bulk-register training schedules from Google Sheets directly into Google Calendar
  • Instantly check room availability and booking overlaps for “Sapporo Office Meeting Room 1” using GAS
  • Automatically send calendar invites (guest invitations) to specified team members
  • Batch clean and delete outdated meetings or old schedules automatically

To kick off this milestone Episode 76, we are learning the foundational method to pinpoint and access any specific calendar: CalendarApp.getCalendarById()!

In this guide, we’ll answer questions like “What exactly is a secondary calendar?”, walk through how to create a secondary calendar step-by-step, look up the necessary “Calendar ID”, write working code to fetch calendar info, and cover common traps beginners often encounter. Let’s make Google Calendar automation simple and approachable!

1. What Is CalendarApp.getCalendarById()?

CalendarApp.getCalendarById() is a Google Apps Script method used to retrieve a specific Google Calendar (a Calendar object) based on its unique “Calendar ID”.

Breaking Down the Basic Code Syntax

var calendar = CalendarApp.getCalendarById("CALENDAR_ID");
  • CalendarApp
    This is the top-level service class that manages Google Calendar features. Calling it tells GAS: “I’m ready to work with Google Calendar!”
  • .getCalendarById("...")
    This is a method called on CalendarApp. It searches for and fetches the calendar matching the specific Calendar ID provided in parentheses.

Difference Between getDefaultCalendar() and getCalendarById()

When fetching calendars in GAS, two primary methods are commonly used:

Method Name Role Real-World Analogy
CalendarApp.getDefaultCalendar() Retrieves the logged-in user’s primary personal calendar Your personal pocket planner
CalendarApp.getCalendarById("ID") Retrieves a specific calendar (secondary or shared calendar) by ID A conference room booking sheet on the wall or a team whiteboard

Why Is getCalendarById() Essential in Practical Work?

You might wonder, “Isn’t it enough to just add events to my own personal default calendar?”

In real business environments, however, teams frequently manage and automate dedicated secondary calendars or shared calendars—such as “Sapporo Office Meeting Room 1”, company-wide event calendars, or project-specific schedules.

To prevent work room bookings from cluttering personal schedules and to automate events for dedicated rooms or teams, mastering getCalendarById() is an absolute must!

2. Beginner Friendly: How to Create a “Secondary Calendar” First

Before running getCalendarById() in our code, let’s create a secondary test calendar in the Google Calendar interface.

A “secondary calendar” is an additional dedicated calendar created under your main Google account. Separating schedules by purpose makes color-coding, toggling visibility, and sharing with colleagues effortless.

For our hands-on example, let’s create a calendar named “Sapporo Office Meeting Room 1”!

Step-by-Step Guide to Creating a Secondary Calendar

STEP 1: Open Google Calendar

Open Google Calendar in your web browser (such as Google Chrome).

STEP 2: Click the “+” Button Next to “Other calendars”

Scroll down the left sidebar until you locate “Other calendars”. Click the “+ (Add other calendars)” icon next to it.

[Screen Layout]
Other calendars  [+]  ← Click here!

STEP 3: Select “Create new calendar”

From the dropdown menu, click “Create new calendar”.

STEP 4: Enter the Calendar Details

On the calendar settings page, fill in the following fields:

  • Name: Sapporo Office Meeting Room 1
  • Description (Optional): Booking calendar for meetings and conferences at the Sapporo Office
  • Time zone: (GMT+09:00) Japan Standard Time - Tokyo

STEP 5: Click “Create calendar”

Once entered, click the blue “Create calendar” button at the bottom. After a few seconds, a confirmation message will display: “[Calendar Name] successfully created”.

Click the back arrow (←) in the upper left corner to return to the main view. You’ll now see “Sapporo Office Meeting Room 1” listed in your calendar list on the left!

3. Crucial Step: How to Find and Check Your Calendar ID

Now that your secondary calendar is ready, let’s locate its “Calendar ID”—the unique address GAS uses to target this specific calendar.

Google Apps Script does not identify calendars by their display names like “Sapporo Office Meeting Room 1”; instead, it identifies them using an internal alphanumeric code known as the Calendar ID.

4 Steps to Find Your Calendar ID

STEP 1: Open the Calendar Options Menu

In the left sidebar list of Google Calendar, hover your mouse over “Sapporo Office Meeting Room 1”. Click the three vertical dots (⋮) that appear on the right.

STEP 2: Select “Settings and sharing”

Click “Settings and sharing” from the pop-up menu.

STEP 3: Locate the “Integrate calendar” Section

Once the settings page opens, click “Integrate calendar” in the left menu or scroll down toward the bottom of the page.

STEP 4: Copy the “Calendar ID”

Under the “Integrate calendar” section, look for the field labeled “Calendar ID”.

The text displayed here is the unique ID for this calendar!

[Calendar ID Examples]
• For a secondary calendar:
  xxxxxxxxxxxxxxxxxxxxxxxxxx@group.calendar.google.com

• For your primary personal calendar:
  your-name@gmail.com (your Google email address)

Make sure to copy this entire string containing @group.calendar.google.com!

4. STEP 1: Hands-On: Fetch and Inspect the “Sapporo Office Meeting Room 1” Calendar in GAS

With your Calendar ID in hand, let’s open the GAS editor and write some code!

In this exercise, we will retrieve the “Sapporo Office Meeting Room 1” calendar, extract its calendar name, time zone, and description, and print them to the execution log.

1. Open Google Sheets and the GAS Editor

  1. Create a new Google Spreadsheet and name it “Sapporo Office Facility Management Sheet”.
  2. In the top menu, navigate to Extensions > Apps Script to open the script editor.

2. Paste the Code

Delete any boilerplate function myFunction() { ... } code in the editor, and copy & paste the following script.

*Be sure to replace the placeholder in var roomCalendarId = "..." with your actual secondary calendar ID copied earlier!

/**
 * Episode 76: Basic verification script for CalendarApp.getCalendarById()
 * Targets and fetches information for the "Sapporo Office Meeting Room 1" calendar.
 */
function getSapporoRoomCalendar() {
  // 1. Prepare the Calendar ID to target (replace with your actual calendar ID)
  var roomCalendarId = "xxxxxxxxxxxxxxxxxxxxxxxxxx@group.calendar.google.com";

  // 2. Fetch the target calendar object using CalendarApp.getCalendarById()
  var targetCalendar = CalendarApp.getCalendarById(roomCalendarId);

  // 3. [Safety Check] Verify if the calendar was fetched successfully (null check)
  if (targetCalendar === null) {
    Logger.log("[ERROR] The specified Calendar ID was not found or access permission is missing.");
    Logger.log("Please verify your Calendar ID: " + roomCalendarId);
    return; // Stop execution here
  }

  // 4. Retrieve properties from the calendar object
  var calendarName = targetCalendar.getName();           // Get calendar name
  var timeZone = targetCalendar.getTimeZone();           // Get time zone
  var description = targetCalendar.getDescription();     // Get calendar description

  // 5. Output to the Execution Log using Logger.log()
  Logger.log("==========================================");
  Logger.log(" Successfully fetched calendar details!");
  Logger.log("- Calendar Name: " + calendarName);
  Logger.log("- Time Zone    : " + timeZone);
  Logger.log("- Description  : " + description);
  Logger.log("==========================================");
}

3. Line-by-Line Code Breakdown

  • var roomCalendarId = "..."
    Stores the target Calendar ID inside a variable. Since it’s a string, always wrap it in quotes ("").
  • CalendarApp.getCalendarById(roomCalendarId)
    The star of today’s lesson! It searches for the calendar with the matching ID and assigns the resulting Calendar object to the targetCalendar variable.
  • if (targetCalendar === null)
    If the calendar could not be found due to a typo or lack of permissions, getCalendarById() returns null (empty value). Attempting to call methods on null causes a runtime crash, so this if statement serves as a vital safeguard.
  • targetCalendar.getName()
    Extracts the display name of the calendar (e.g., “Sapporo Office Meeting Room 1”).
  • targetCalendar.getTimeZone()
    Retrieves the time zone configured for the calendar (e.g., “Asia/Tokyo”).
  • targetCalendar.getDescription()
    Retrieves the description entered during calendar setup.

4. Initial Run and Authorizing Permissions

Once your code is pasted, click the Save disk icon at the top, ensure the function dropdown shows getSapporoRoomCalendar, and click Run.

When running a script that accesses Google Calendar for the first time, the “Authorization required” security dialogue will appear.

Authorization Steps (Quick Review)

  1. Click the “Review permissions” button.
  2. Select your Google account.
  3. When the warning “Google hasn’t verified this app” appears, click “Advanced” in the lower left.
  4. Click “Go to Untitled project (unsafe)” at the bottom.
  5. Click “Allow” on the final screen.

5. Checking the Execution Log

After authorization is complete, the function executes automatically. Check the “Execution log” at the bottom of the editor. If you see output like this, congratulations—it’s a success!

Info    ==========================================
Info     Successfully fetched calendar details!
Info    - Calendar Name: Sapporo Office Meeting Room 1
Info    - Time Zone    : Asia/Tokyo
Info    - Description  : Booking calendar for meetings and conferences at the Sapporo Office
Info    ==========================================

GAS identified the Calendar ID and successfully retrieved all the metadata for “Sapporo Office Meeting Room 1”!

5. 5 Common Traps Beginners Encounter (and How to Fix Them)

When working with getCalendarById(), beginners frequently hit a few common snags. Understanding these pitfalls in advance will save you tons of debugging time!

Trap 1: Passing the Calendar Name Instead of the Calendar ID

✗ Incorrect Code

// Passing the calendar's display name directly
var calendar = CalendarApp.getCalendarById("Sapporo Office Meeting Room 1");

✓ Correct Code

// Always pass the alphanumeric ID ending in @group.calendar.google.com
var calendar = CalendarApp.getCalendarById("xxxxxxxxxx@group.calendar.google.com");

The “Id” in getCalendarById() refers to the alphanumeric Calendar ID found in settings, not the user-friendly title. Passing a calendar title will return null because no calendar matches that ID.

Trap 2: Accidental Whitespace When Copying the ID

A very frequent issue when copying the ID from the settings page is accidentally grabbing a leading or trailing whitespace.

// ✗ Trailing space inside quotes (hard to spot visually!)
var calendar = CalendarApp.getCalendarById("xxxxxxxxxx@group.calendar.google.com ");

Even a single extra space causes Google to treat the string as a completely different, non-existent ID. After pasting, always check that no unintended spaces are lingering inside quotes " "!

Trap 3: Target Calendar Lacks Access Permissions

If you specify someone else’s personal calendar ID (e.g., colleague@gmail.com) or an internal calendar from another team without granted permissions, GAS cannot access it for security reasons and returns null.

For shared calendars, open “Settings and sharing” in Google Calendar beforehand and confirm that your account has been granted at least “See all event details” or “Make changes to events” access.

Trap 4: TypeError: Cannot read properties of null (reading ‘getName’)

You might see this red error message appear during execution:

TypeError: Cannot read properties of null (reading 'getName')

Cause

This happens when CalendarApp.getCalendarById() fails to find the calendar and returns null, and your code immediately attempts to call null.getName().

Solution

Always include a null-check guard statement using if (targetCalendar === null), exactly as demonstrated in our sample script!

var targetCalendar = CalendarApp.getCalendarById(roomCalendarId);

if (targetCalendar === null) {
  Logger.log("Failed to retrieve calendar. Please verify the Calendar ID.");
  return; // Safely exit execution
}

Trap 5: Access Blocked When Running Standalone Scripts

Standalone scripts created via Google Drive (New > Google Apps Script) can sometimes encounter permission boundaries more easily when managing domain calendars.

When starting out, creating container-bound scripts via your management sheet’s Extensions > Apps Script is the most reliable, problem-free approach.

6. Real-World Use Cases and Workflow Ideas

Beyond simple lookups, CalendarApp.getCalendarById() is the essential launchpad for nearly all advanced calendar automation workflows.

Here are a few practical ways you can combine it in daily operations:

[Practical Automation Workflow Example]

  [Google Sheet: Sapporo Office Meeting Room Booking Log]
            │
            ▼ (1) Read date/time, meeting title, and organizer from sheet rows
  [GAS Program]
            │
            ▼ (2) Target the room via CalendarApp.getCalendarById("Room 1 ID")
  [Sapporo Office Meeting Room 1 Calendar]
            │
            ▼ (3) Automatically create calendar entries with Calendar.createEvent()!
  [Event instantly appears on Google Calendar!]
  1. Room Double-Booking Prevention System
    When a booking request is submitted via a Google Sheet, GAS uses getCalendarById() to access “Sapporo Office Meeting Room 1” and checks whether any conflicting events already occupy that time slot.
  2. Automated Project Milestone Sync
    Fetch a shared team calendar by ID and populate development milestones directly from a Google Sheets project roadmap in a single click.
  3. Shift Roster Sync to Individual Calendars
    Loop through employee shift records in a spreadsheet and dynamically target each staff member’s calendar by their individual email/ID to push their assigned work shifts.

7. Summary and What’s Next

In this tutorial, we took a deep dive into the fundamental method for retrieving specific calendars: CalendarApp.getCalendarById()!

Key Takeaways

  1. CalendarApp.getCalendarById("ID") retrieves the calendar object associated with the provided ID.
  2. It is essential for automating secondary and shared calendars (like meeting rooms or team boards), not just your default personal calendar.
  3. Find your Calendar ID under Google Calendar > “Settings and sharing” > “Integrate calendar”.
  4. Provide the unique ID string (often ending in @group.calendar.google.com), never the display title.
  5. Always implement an if (targetCalendar === null) check to safely handle missing calendars or permission errors.

Now that you know how to grab the right calendar target in GAS, our next step is to create new calendar events automatically on that schedule!

In the next episode, we’ll cover Calendar.createEvent() / createAllDayEvent()!

We’ll learn how to write code that schedules timed meetings and all-day events on “Sapporo Office Meeting Room 1” in seconds. Stay tuned!