Home > Mobile >  Google app script delete event from 2 possible calendar
Google app script delete event from 2 possible calendar

Time:07-04

I would like to delete calendar event form 2 possible calendar. I try to define 2 calendar IDs using OR || but if calendar id return null on first try the deleteevent become error. Anyone can help?

var calendarId = "calendarID1" || "calendarID2" ;
var eveId = 2;
//var typeId = 3;

function deleteEvent() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
  var lr = rows.getLastRow();

  var eventID = sheet.getRange(lr, eveId, 1, 1).getValue();
  //var type = sheet.getRange(lr, typeId, 1, 1).getValue();

  var cal = CalendarApp.getCalendarById(calendarId);
  var event = cal.getEventSeriesById(eventID);
  event.deleteEventSeries();

}

CodePudding user response:

Description

A few things about my coding preferences first. I always wrap my code in a try{} catch(err){} block. That way if I make a coding mistake it shows up and if there is an error during execution during testing it shows up in the Execution transcript. If you are testing through script editor you could replace Logger.log with console.log. Secondly, I avoid global variables. I've also eliminated some of your redundant code.

Your code var calendarId = "calendarID1" || "calendarID2" ; would result in calendarId = false, not an Id. Instead use an array to contain both Ids. Then use an Array.forEach() to loop through the Ids as shown below.

Code.gs

function deleteEvent() {
  try {
    var calendarIds = ["calendarID1","calendarID2"];
    var eveId = 2;
    var sheet = SpreadsheetApp.getActiveSheet();
    var rows = sheet.getDataRange();
    var lr = rows.getLastRow();

    var eventID = sheet.getRange(lr, eveId, 1, 1).getValue();
    //var type = sheet.getRange(lr, typeId, 1, 1).getValue();

    calendarIds.forEach( calendarId => {
        let cal = CalendarApp.getCalendarById(calendarId);
        let event = cal.getEventSeriesById(eventID);
        if( event) event.deleteEventSeries();
      }
    );
  }
  catch(err) {
    Logger.log(err);
  }
}

Reference

  • Related