Home > Blockchain >  Google App Script - Add or Update Calendar Event
Google App Script - Add or Update Calendar Event

Time:08-13

Updating previous question with detailed example. I have a google sheet with three used columns (A: Event Title, B: Event Description, and D: Event Date). I want to create a new all day event on Google Calendar if none exists, and update the existing one if it already exists.

Here is the code I tried: I am getting the error: TypeError: Cannot read property 'setDescription' of undefined

function updatecal(){
  var cal = CalendarApp.getCalendarById('[email protected]');
  var data = SpreadsheetApp.getActive().getSheetByName("Data For Calendar");
  const rows = data.getDataRange().getValues();
  rows.forEach(function(row, index){
    if (index === 0) return;
    var eventdate = data.getRange(index, 4, 1, 1).getValue();
    var eventtitle = data.getRange(index,1,1,1).getValue();
    var eventdescription = data.getRange(index,2,1,1).getValue();
    console.log(eventdate   eventtitle   eventdescription)
    const eventdate1 = new Date(eventdate)
    const events = cal.getEventsForDay(eventdate1);
    if (events.lenght == 0){
      var newevent = cal.createAllDayEvent(eventtitle,eventdate1,
    {description: eventdescription});
    } else {
      ev = events[0];
      ev.setDescription(eventdescription)
    }

  })

}

CodePudding user response:

There is a typo in line 13 inside the if statement. You wrote lenght instead of length If you fix that the code runs just fine and the calendar events are created without any problem.

function updatecal(){
  var cal = CalendarApp.getCalendarById('[email protected]');
  var data = SpreadsheetApp.getActive().getSheetByName("Data For Calendar");
  const rows = data.getDataRange().getValues();
  rows.forEach(function(row, index){
    if (index === 0) return;
    var eventdate = data.getRange(index, 4, 1, 1).getValue();
    var eventtitle = data.getRange(index,1,1,1).getValue();
    var eventdescription = data.getRange(index,2,1,1).getValue();
    console.log(eventdate   eventtitle   eventdescription)
    const eventdate1 = new Date(eventdate)
    const events = cal.getEventsForDay(eventdate1);
    if (events.length == 0){          //The error was in this line
      var newevent = cal.createAllDayEvent(eventtitle,eventdate1,
    {description: eventdescription});
    } else {
      ev = events[0];
      ev.setDescription(eventdescription)
    }

  })

}

References:

  • Related