[GAS Beginner Series #80] Delete Google Calendar Events Automatically: CalendarEvent.deleteEvent() Tutorial

Once you learn how to automatically create Google Calendar events and invite guests with Google Apps Script (GAS), the next challenge you will inevitably face is dealing with obsolete, canceled, or duplicate meetings.

“A meeting schedule was changed, but the old event stayed on the calendar, causing double-bookings in the conference room…”

“Last-minute cancellations left ghost events behind, cluttering the entire team’s schedule…”

Manually opening each event in Google Calendar and clicking the trash can icon is tedious and prone to human error. Forgotten old events can quickly derail your team’s workflow.

In this 80th installment of our series, we will take a deep dive into CalendarEvent.deleteEvent(), the essential Google Apps Script method for instantly canceling and deleting obsolete or duplicate events programmatically!

Using our familiar Sapporo Office Meeting Room 1 calendar as our practical scenario, we will cover everything from basic syntax to real-world business automations, common pitfalls to avoid, and safe testing techniques.

1. What Is CalendarEvent.deleteEvent()?

CalendarEvent.deleteEvent() is a method invoked on an individual event (a CalendarEvent object) that permanently deletes (cancels) that specific event from Google Calendar.

Understanding the Hierarchy: CalendarApp vs. Calendar vs. CalendarEvent

Back in episodes 2 through 4, we explored the hierarchy of spreadsheets: “House (Spreadsheet file) > Room (Sheet) > Furniture (Cell)”. Google Calendar operations follow the exact same structural model!

  • [Entire App] = CalendarApp
    The top-level service managing all Google Calendar features in GAS.
  • [Calendar Container (Room)] = Calendar (covered in Episode 76)
    Represents a specific calendar instance, such as “Sapporo Office Meeting Room 1” or your primary personal calendar.
  • [Event Card (Furniture)] = CalendarEvent (covered in Episodes 77–79)
    Represents an individual event card placed inside a calendar, such as a “Monthly Review” or “Weekly Team Sync”.
[ CalendarApp (Entire App) ]
         ↓
   [ Calendar (Calendar Container) ]  ← e.g., Sapporo Office Meeting Room 1
            ↓
      [ CalendarEvent (Individual Event) ]  ← ★ Today's Target!

The CalendarEvent.deleteEvent() method corresponds precisely to taking one of those individual event cards (CalendarEvent) and tossing it into the trash or running it through a shredder.

Basic Syntax

// 1. Fetch the target event (CalendarEvent) from the calendar
var events = calendar.getEvents(startTime, endTime);
var event = events[0]; // Select the first event

// 2. Delete the retrieved event!
event.deleteEvent();

The most crucial takeaway here is that you call this method on the CalendarEvent (the individual event), not directly on the Calendar object.

2. STEP 1: Preparation — Setting Up Sapporo Office Meeting Room 1 and Test Events

Let’s prepare our sandbox environment so we can safely practice deleting events using Google Apps Script!

Step-by-Step Setup

  1. Open Google Calendar
    Navigate to Google Calendar in your web browser.
  2. Retrieve Your Calendar ID (Review from Episode 76)
    Open “Settings and sharing” for the calendar you want to manage (e.g., “Sapporo Office Meeting Room 1” or a dedicated test calendar). Under the “Integrate calendar” section, copy the Calendar ID (e.g., c_xxxxxxx@group.calendar.google.com). Note: If you are testing this on your personal default calendar, you can simply use CalendarApp.getDefaultCalendar() instead of a Calendar ID!
  3. Create Test Events in Your Calendar
    For testing purposes, manually add the following three events to today’s schedule (or generate them using your script from Episode 77):
Event Title Time Slot Status
[OLD] Sapporo Team Weekly Meeting Today 10:00 – 11:00 Obsolete event to delete
[CONFIRMED] Sapporo Team Weekly Meeting Today 11:00 – 12:00 Active event to keep
[OLD] Sapporo Office Facility Inspection Today 14:00 – 15:00 Obsolete event to delete

Once your test events are in place, open your Google Sheets menu bar and click Extensions > Apps Script to launch the script editor!

3. STEP 2: Hands-On Practice — Automatically Deleting Obsolete Meeting Events

Now that setup is complete, let’s write a script that scans today’s events, automatically identifies any obsolete meetings containing “[OLD]” in their title, and deletes them.

1. Enter the Script

Clear any existing code in the Apps Script editor and paste the following script:

function deleteOldMeetings() {
  // 1. Get "Sapporo Office Meeting Room 1" by its Calendar ID (Episode 76)
  var calendarId = "YOUR_CALENDAR_ID@group.calendar.google.com"; // ★ Replace with your actual Calendar ID
  var calendar = CalendarApp.getCalendarById(calendarId);
  
  // 2. Set the search range for the entire day today
  var now = new Date();
  var startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
  var endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
  
  // 3. Retrieve today's events as an array (Episode 78)
  var events = calendar.getEvents(startTime, endTime);
  Logger.log("Today's events: " + events.length);
  
  // 4. Iterate through the retrieved events one by one
  for (var i = 0; i < events.length; i++) {
    var event = events[i];
    var title = event.getTitle(); // Get the event title
    
    // Check if the title contains "[OLD]"
    if (title.indexOf("[OLD]") !== -1) {
      Logger.log("Target for deletion found: " + title);
      
      // ★ The star of the show: delete the event from the calendar
      event.deleteEvent();
      
      Logger.log(" └ Event successfully canceled and deleted!");
    } else {
      Logger.log("Keep event: " + title);
    }
  }
}

2. Line-by-Line Code Explanation

  • var calendar = CalendarApp.getCalendarById(calendarId);
    Learned in Episode 76, this retrieves the Calendar object representing the specific room container for the provided ID.
  • var events = calendar.getEvents(startTime, endTime);
    Learned in Episode 78, this queries the calendar and retrieves all events scheduled between 00:00:00 and 23:59:59 today as an array ([event1, event2, ...]).
  • for (var i = 0; i < events.length; i++) { ... }
    A standard loop that processes each event in the array sequentially.
  • if (title.indexOf("[OLD]") !== -1)
    JavaScript’s indexOf() method checks whether a string contains a target substring. If “[OLD]” exists in the title, it returns the index position (not -1), identifying the event as an obsolete entry marked for deletion.
  • event.deleteEvent();
    The key method of this lesson! Calling .deleteEvent() directly on the matching CalendarEvent object removes that event from Google Calendar in a single operation.

3. Save and Run the Script

  1. Replace YOUR_CALENDAR_ID@group.calendar.google.com with your actual Calendar ID.
  2. Click the Save (floppy disk icon) at the top of the editor, ensure deleteOldMeetings is selected in the function dropdown, and click Run.
  3. (If this is your first time running calendar scripts, a Google authorization dialog will appear. Follow the prompts to grant the necessary permissions.)

4. Verify the Execution Results

Check the Execution Log at the bottom of the editor. If your output looks similar to this, the script executed flawlessly:

Info    Today's events: 3
Info    Target for deletion found: [OLD] Sapporo Team Weekly Meeting
Info     └ Event successfully canceled and deleted!
Info    Keep event: [CONFIRMED] Sapporo Team Weekly Meeting
Info    Target for deletion found: [OLD] Sapporo Office Facility Inspection
Info     └ Event successfully canceled and deleted!

Switch over to your Google Calendar interface to inspect the schedule.

Both “[OLD] Sapporo Team Weekly Meeting” and “[OLD] Sapporo Office Facility Inspection” are completely gone, leaving only “[CONFIRMED] Sapporo Team Weekly Meeting” on the board.

Your script successfully located and cleaned up the redundant entries without touching valid bookings!

4. STEP 3: Real-World Use Cases — 3 Advanced Patterns with deleteEvent()

Beyond simple string matching, combining deleteEvent() with Google Sheets or email notifications unlocks powerful business process automations. Let’s look at three practical patterns commonly used in production environments.

Pattern 1: Batch Deleting Multiple Keywords (e.g., “[Canceled]” and “[Postponed]”)

This snippet searches ahead across the upcoming week and removes any meetings tagged with cancellation keywords.

function deleteCanceledEvents() {
  var calendar = CalendarApp.getDefaultCalendar();
  var now = new Date();
  var future = new Date(now.getTime() + (7 * 24 * 60 * 60 * 1000)); // Next 7 days
  
  var events = calendar.getEvents(now, future);
  
  events.forEach(function(event) {
    var title = event.getTitle();
    // Delete events containing "[Canceled]" or "[Postponed]"
    if (title.includes("[Canceled]") || title.includes("[Postponed]")) {
      event.deleteEvent();
      Logger.log("Deleted: " + title);
    }
  });
}

Pattern 2: Syncing Cancellations from a Google Sheets Booking List

In this workflow, the script reads cancellation requests submitted to a Google Sheet (using Range.getValues() from Episode 13) and automatically removes the corresponding events from the calendar.

function syncCancellationsFromSheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var values = sheet.getDataRange().getValues(); // Fetch all sheet data
  var calendar = CalendarApp.getCalendarById("YOUR_CALENDAR_ID@group.calendar.google.com");
  
  // Loop through data rows starting from row 2 (skipping header)
  for (var i = 1; i < values.length; i++) {
    var status = values[i][3]; // Column D: Status (e.g., "Cancel Requested")
    var eventTitle = values[i][1]; // Column B: Booking Title
    
    if (status === "Cancel Requested") {
      // Search today's calendar events and delete the match
      var events = calendar.getEventsForDay(new Date());
      events.forEach(function(event) {
        if (event.getTitle() === eventTitle) {
          event.deleteEvent(); // Delete from Google Calendar
          sheet.getRange(i + 1, 4).setValue("Deleted"); // Update status using setValue (Episode 6)!
        }
      });
    }
  }
}

Pattern 3: Sending Email Notifications upon Deletion to Prevent Accidental Loss

When automating deletions, sending an audit email to team administrators via GmailApp.sendEmail() (learned in Episode 32) creates a safe paper trail and keeps everyone informed.

// Send an email notification immediately after deletion
event.deleteEvent();
GmailApp.sendEmail("sapporo-admin@example.com", "[Auto-Notification] Calendar Event Deleted", "The following event was automatically deleted:\n" + title);

5. Troubleshooting: 4 Common Pitfalls and How to Avoid Them

Here are four frequent errors and operational headaches beginners encounter when using CalendarEvent.deleteEvent(), along with step-by-step solutions.

Pitfall 1: Calling calendar.deleteEvent() Triggers a TypeError

This is by far the most common syntax mistake among newcomers!

// ✕ Incorrect: Calling deleteEvent directly on the Calendar object
var calendar = CalendarApp.getCalendarById(id);
calendar.deleteEvent(); // Error! TypeError: calendar.deleteEvent is not a function

// ◯ Correct: Calling deleteEvent on an individual CalendarEvent object
var events = calendar.getEvents(start, end);
events[0].deleteEvent();

Cause and Solution:

deleteEvent() is a method belonging to the CalendarEvent class (the individual card), not the Calendar class (the room container).

To delete an event, you must first locate and isolate that specific CalendarEvent object using methods like getEvents() or getEventsForDay(), and then invoke .deleteEvent() on it.

Pitfall 2: Deleting Recurring Events (Single Instance vs. Entire Series)

If you call deleteEvent() on a recurring event (such as a weekly team meeting), Google Apps Script defaults to deleting only that single day’s instance.

  • event.deleteEvent(): Deletes only the selected occurrence (all future and past weeks remain intact).
  • event.getEventSeries().deleteEventSeries(): Deletes the entire series across all past and future recurrences using the EventSeries API.

Be intentional about your choice depending on whether you are canceling a one-off date or canceling the recurring meeting series permanently.

Pitfall 3: Insufficient Access Permissions (“You do not have permission”)

If you attempt to delete events on a calendar owned by another user where you only possess “See all event details” (read-only) permissions, Google will throw an authorization error.

Solution:

To delete or modify calendar events via GAS, your Google account must hold “Make changes to events” or “Make changes and manage sharing” permissions on that calendar. Check the sharing settings in Google Calendar before running your script.

Pitfall 4: Accidentally Deleting Critical Events (No “Ctrl + Z” Undo in GAS!)

A vital rule of thumb for automation scripts: Calendar events deleted via Google Apps Script cannot be restored with Ctrl + Z!

If an incorrect search condition deletes an executive meeting or important client visit, recovery can be very painful. Protect yourself by practicing dry runs!

Best Practice: Perform a Dry Run First

Always comment out the event.deleteEvent() line with // on your first execution. Check the output logs in Logger.log() to ensure only the intended events match your condition.

// Example of a safe dry run check
if (title.indexOf("[OLD]") !== -1) {
  Logger.log("[DRY RUN] Would delete: " + title);
  // event.deleteEvent(); // ← Keep commented out until verified in the logs!
}

Once you review the execution logs and confirm that your filters are working safely, uncomment the deletion line for production. This is standard operating procedure for seasoned engineers!

6. Summary and What’s Next

In this tutorial, we covered how to programmatically remove obsolete and duplicate events using CalendarEvent.deleteEvent() in Google Apps Script.

Key Takeaways

  1. deleteEvent() is invoked on individual CalendarEvent objects, not on the parent Calendar object.
  2. Retrieve event lists using getEvents(), loop through them, and target items using string checks like indexOf() or includes().
  3. Integrating with Google Sheets (getValue) and automated emails (sendEmail) enables resilient end-to-end booking automations.
  4. Deletions are permanent in GAS, so always execute a dry run using Logger.log() before unleashing live deletions.

With this lesson, you have officially completed Phase 8: Google Calendar Integration (Episodes 76 through 80)!

From accessing and creating calendars to fetching schedules, inviting team members, and deleting events, you now possess comprehensive skills for Google Calendar automation.

🚀 Next Up: Phase 9 — Building Web Apps with GAS!

Starting next episode, we kick off one of the most exciting phases of this entire series: Phase 9: Web App Development (Episodes 81–90)!

We will transform your backend scripts and spreadsheet automations into full-fledged, interactive web applications accessible right in the browser.

In Episode 81, we’ll dive into doGet(e) and create the landing portal for our “Sapporo Office Integrated Dashboard Web App”!

We will explain how doGet(e) delivers HTML content when users visit your script’s URL. It’s your first step toward building custom web tools, so stay tuned!