I'm working on a spreadsheet for my department to create, edit, and delete work assignments to a google calendar. It's been quite a while since I did any actual coding, so I've been doing a lot of trial and error and referring to the Google App Script and Calendar references. I've finally gotten to the point where I can create the events; however, when I am testing my function to delete events, I've discovered that the event on row two, deletes the event on row three, and when I try to delete the event on row three, I get a "cannot call method deleteEvent" error. I've tried looking through various sites for similar situations and have not been successful. Any help walking me through the error in my code issue would be greatly appreciated. I'm also attempting to attach a link for a video of the spreadsheet as the script is running here
// Adds the custom menu to the active spreadsheet.
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{
name: "Create New Events",
functionName: "createCalEvent"
}, {
name: "Update Existing Events",
functionName: "updateCalEvent"
}, {
name: "Delete Existing Events",
functionName: "deleteCalEvent"
}
];
spreadsheet.addMenu('Calendar Options', menuEntries);
}
// Event Status --> Assist in Triggering Update/Delete Functions
var delConfirmed = 'Event Created';
var updateConfirmed = 'Event Updated';
var eventCreate = 'Event Deleted';
function createCalEvent(){
var calSheet = SpreadsheetApp.getActiveSheet();
var dataRange = calSheet.getRange('$A2:$J');
var data = dataRange.getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var calDate = row[1]; // COL A
var calTitle = row[5]; // COL F
var calGuests = row[6]; // COL G
var calEType = row[7]; // COL H
var calID = row[8]; // COL I
var calStatus = row[9]; // COL J
// If there is a date and both the Event Type (Adjust/Delete) and Status are blank then Create the Calendar Event
if(calDate !=='' && calEType == '' && calStatus == ''){
var calEvent = CalendarApp
.getCalendarById('envysion.com_kmfeb8mqmlv4j9k34l37q7fv3k#group.calendar.google.com')
.createAllDayEvent(calTitle, new Date(calDate),{guests:calGuests});
// Update the Status Column
SpreadsheetApp.getActiveSheet().getRange(i+2, 10).setValue('Event Created');
var newEvent = calEvent.getId();
// Add the Event ID to the Event ID Column
SpreadsheetApp.getActiveSheet().getRange(i+2,9).setValue(newEvent);
Logger.log('Event ID: ' + newEvent + ' Title: ' + calEvent.getTitle() + 'Guests: ' + calEvent.getGuestList());
}
}
}
function deleteCalEvent()
{
// Get range of dates to delete
var fromDate = new Date(2019,3,1);
var toDate = new Date(2019,4,1);
// Get Calendar Events
var calendar = CalendarApp.getCalendarById('envysion.com_kmfeb8mqmlv4j9k34l37q7fv3k#group.calendar.google.com')
var events = calendar.getEvents(fromDate, toDate);
// Get Spreadsheet Details
var calSheet = SpreadsheetApp.getActiveSheet();
var dataRange = calSheet.getRange('$A2:$J');
var data = dataRange.getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var calDate = row[1];
var calTitle = row[5];
var calGuests = row[6];
var calEType = row[7];
var calID = row[8];
var calStatus = row[9];
// Check if the Type column is set to Delete and if the event hasn't already been deleted
if(calEType == 'Delete' && calStatus !== 'Event Deleted'){
events[i].deleteEvent();
SpreadsheetApp.getActiveSheet().getRange(i+2, 10).setValue('Event Deleted');
SpreadsheetApp.getActiveSheet().getRange(i+2, 9).setValue('');
}
}
}
It seems you need do something like this
if(calEType == 'Delete' && calStatus !== 'Event Deleted'){
var _event_ = calendar.getEventById(calStatus);
if(_event_){
_event_.deleteEvent();
SpreadsheetApp.getActiveSheet().getRange(i+2, 10).setValue('Event Deleted');
SpreadsheetApp.getActiveSheet().getRange(i+2, 9).setValue('');
}
}
This is because you may have a different number of events in the calendar and in the sheet.
Related
Absolute noob here !
Background:
am trying to create a Google Sheet which I can update for a series of events and
create Google Calendar events based on those entries
so far, am successful in creating calendar events and also updating back the last column of the sheet with the EventID (iCalUID) - thanks to other stackoverflow posts
am also successful in not creating Duplicates by checking if the EventID (iCalUID) is already present in the last column - thanks again to other stackoverflow posts
But... have another requirement, where am failing:
need to mark an existing event as 'Cancelled' in one of the columns in the sheet and
if this is 'true' then look-up the EventID (iCalUID) from the corresponding last cell (of that row which has a 'Cancelled' entry) and
delete that particular event from the calendar
also, calendar events should NOT be created again as long as that cell remains/retains the word 'Cancelled'.
the "var check1 = row[23]; //Booked/Blocked/Cancelled" in below script was just added to bring in this logic that I wanted, but am kind of unable to proceed
Relevant screen-shot of the sheet
Code that I used so far as below:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Sync to Calendar')
.addItem('Sync Now', 'sync')
.addToUi();
}
function sync() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var calendar = CalendarApp.getCalendarById('myemailid#gmail.com');
var startRow = 2; // First row from which data should process > 2 exempts my header row
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var name = row[1]; //Name of Guest
var place = row[4]; //Add2
var room = row[9]; //Room Number
var inDate = new Date(row[10]); //Check-In Date
var outDate = new Date(row[11]); //Check-Out Date
var check1 = row[23]; //Booked/Blocked/Cancelled
var check2 = row[24]; //Event created and EventID (iCalUID) populated
if (check2 == "") {
var currentCell = sheet.getRange(startRow + i, numColumns);
var event = calendar.createEvent(room, inDate, outDate, {
description: 'Booked by: ' + name + ' / ' + place + '\nFrom: ' + inDate + '\nTo: ' + outDate
});
var eventId = event.getId();
currentCell.setValue(eventId);
}
}
}
I believe your goal is as follows.
You want to check the columns "X" and "Y".
When the column "X" is not Cancelled and the column "Y" is empty, you want to create a new event.
When the column "X" is Cancelled and the column "Y" is not empty, you want to delete the existing event.
When the column "X" is Cancelled, you don't want to create a new event.
In this case, how about the following modification?
Modified script:
In this script, in order to check whether the event has already been deleted, Calendar API is used. So please enable Calendar API at Advanced Google services.
function sync() {
var calendarId = 'myemailid#gmail.com'; // Please set your calendar ID.
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var calendar = CalendarApp.getCalendarById(calendarId);
var startRow = 2; // First row from which data should process > 2 exempts my header row
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows - 1, numColumns);
var data = dataRange.getValues();
var done = "Done"; // It seems that this is not used.
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var name = row[1]; //Name of Guest
var place = row[4]; //Add2
var room = row[9]; //Room Number
var inDate = new Date(row[10]); //Check-In Date
var outDate = new Date(row[11]); //Check-Out Date
var check1 = row[23]; //Booked/Blocked/Cancelled
var check2 = row[24]; //Event created and EventID (iCalUID) populated
// I modified below script.
if (check1 != "Cancelled" && check2 == "") {
var currentCell = sheet.getRange(startRow + i, numColumns);
var event = calendar.createEvent(room, inDate, outDate, {
description: 'Booked by: ' + name + ' / ' + place + '\nFrom: ' + inDate + '\nTo: ' + outDate
});
var eventId = event.getId();
currentCell.setValue(eventId);
} else if (check1 == "Cancelled" && check2 != "") {
var status = Calendar.Events.get(calendarId, check2.split("#")[0]).status;
if (status != "cancelled") {
calendar.getEventById(check2).deleteEvent();
}
}
}
}
Reference:
Events: get
See code below: It's set to update on calendar event.
But events are still duplicating onto the sheet.
Can you take a look and see where I went wrong?
get only new created events - is there a way to getevents by created date (now)?
}
var events = calendar.getEvents(start, end);
var eventDetails = [];
var eventarray = new Array();
for(var i = 0; i<events.length; i++){
eventDetails.push([events[i].getLocation(), events[i].getTitle(), events[i].getDescription(), events[i].getStartTime()]);
}
var startRow = sheet.getLastRow();
var startCol = 2;
for(var j = 0; j<eventDetails.length; j++){
var tempRange = sheet.getRange(startRow+j,startCol, 1, 4);
var eventArray = new Array(eventDetails[j]);
tempRange.setValues(eventArray);
}
//Here lies the problem code//
for(i in eventDetails){
var row = eventDetails[i];
var duplicate = false;
for(j in eventArray){
if(row.slice(0,2).join() == eventArray[j].slice(0,2).join()){
duplicate = true;
}
}
}
if(!duplicate){
eventArray.push(row);
{
return eventArray;
ss.sort(2, true);
}
}
}
Issue:
You have a sheet with data from a list Calendar events.
You want a script to retrieve and write any new events, ignoring the ones already in the sheet.
You identify an event through its location, title and description.
Solution:
If all this is correct, then you can do the following:
After retrieving the events from the calendar, use map() to retrieve the event details.
If there are any old events in the sheet, filter them out of your eventDetails array, using filter() and every() (the second parameter of slice() is exclusive so, if you want to compare the three first properties, it should be slice(0,3) instead of slice(0,2)).
If the filtered array of eventDetails is not empty (that is, there are new events in the Calendar), write those new events to your sheet.
Code sample:
function importCalendar(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); //Target sheet for events
var calendarName = sheet.getRange('C2').getValue(); //name of calendar ex. calendar#gmailcom
var start = sheet.getRange('C3').getValue(); //to date
var end = sheet.getRange('C4').getValue(); //from date
var calendar = CalendarApp.getCalendarById(calendarName);
if(!calendar) calendar = CalendarApp.getCalendarsByName(calendarName)[0];
var events = calendar.getEvents(start, end);
var eventDetails = events.map(event => [event.getLocation(), event.getTitle(), event.getDescription(), event.getStartTime()]);
var lastRow = sheet.getLastRow();
var startCol = 2; // Column where the event list starts
var oldStartRow = 8; // Row where the event list starts
var numCols = 4; // Number of event fields
var numRows = lastRow - oldStartRow + 1;
if (numRows !== 0) { // If there are events in the sheet, filter the duplicates
var oldEvents = sheet.getRange(oldStartRow, startCol, lastRow - oldStartRow + 1, numCols).getValues();
// Filter out duplicates:
eventDetails = eventDetails.filter(eventRow => oldEvents.every(oldEvent => oldEvent.slice(0,3).join() != eventRow.slice(0,3).join()));
}
if (eventDetails.length != 0) { // Check if there is any new event coming from the Calendar
sheet.getRange(lastRow + 1, startCol, eventDetails.length, eventDetails[0].length).setValues(eventDetails);
}
}
I've read through a number of posts on SO and elsewhere as to how to prevent a script from continuing to add duplicate calendar events each time it's run. I've been unsuccessful so far in stopping the duplicates.
Here's my code:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Push to Calendar", functionName: "sendCalendarEvents"} ];
ss.addMenu("Custom Menu", menuEntries);
}
function sendCalendarEvents() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange('G1').getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
var lastRow = spreadsheet.getLastRow();
var count = spreadsheet.getRange("A3:E"+lastRow+"").getValues();//five columns
var minutesBefore = 462
for (x=0; x<count.length; x++) {
var row = count[x];
var title = row[0];
var startTime = row[1];
var endTime = row[2];
var guests = row[3];
var description = row[4];
var location = row[5];
var id = row[7];no row[7]
var options = {
'location': location,
'description': description,
'guests':guests +',',
'sendInvites': 'True',
}
if(!id) {
var event = eventCal.createAllDayEvent(title, startTime, options);
var newEventId = event.getId();
spreadsheet.getRange(x+3,7).setValue('yes');
spreadsheet.getRange(x+3,8).setValue(newEventId);
event.addEmailReminder(minutesBefore);
Logger.log('Event ID: ' + event.getId());
and here's my spreadsheet (with 'test' data)
I've also tried variations of the 'if' statement (like if (row[x][7] != 'yes')...create the event) but that hasn't worked either.
Any help? After the duplicate issue is resolved, I then want to be able to have a user edit the date or title or such of an event in the spreadsheet and have the existing event deleted and then a new event (with the updated title/date) be created...if that's possible.
Thanks for any help you can provide!
You only have five columns in your data. There is no row[7]
var count = spreadsheet.getRange("A3:E"+lastRow+"").getValues();//only five columns in your data
var minutesBefore = 462
for (x=0; x<count.length; x++) {
var row = count[x];
var title = row[0];
var startTime = row[1];
var endTime = row[2];
var guests = row[3];
var description = row[4];
var location = row[5];
var id = row[7];//Problem is right here...there is no row[7];
I have a script which has been running for almost 2 years. I update the sheet with dates and either the event is deleted/created or a new one is created.
This last time I went through and added my dates its normal it populates the sheet cell with the event id and I am on my merry way -- however when I go to the calendar nothing shows up for that date/time.
Is there something I am missing like a new permission -- there are no errors thrown -- nothing in the logs. I have an event id but I dont know how to check what is showing up as I cannot see it on the calendar -- Is there a way to check the event id and see what it contains.
The sheet (I separated with pipes)
Subject|Start Date|Start Time|End Date|End Time|All day event|Meeting Organizer|Description|Location|Reminder Date|Reminder Time|Show time as|Event ID|Status
Survey Edit: Science of HC Delivery|08/07/2017|12:00:00 AM|8/7/2017|12:00:00 PM|TRUE|Seamore Butz|||8/7/2017|9:00:00 AM|3 sg5a7jsakgbj8g5rejeos15lhc#google.com|y
function pushToCalendar()
{
//spreadsheet variables
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
/*
getRange (row,column,optNumRows,optNumColumns)
row --- int --- top row of the range
column --- int--- leftmost column of the range
optNumRows --- int --- number of rows in the range.
optNumColumns --- int --- number of columns in the range
*/
var range = sheet.getRange(2,1,lastRow,13);
var values = range.getValues();
//calendar variables
// xxxxxxxxxxxxxxxxxxxxxxxxxx#group.calendar.google.com
var calendar = CalendarApp.getCalendarById('xxxxxxxxxxxxxxxxxxxxx#group.calendar.google.com')
var numValues = 0;
for (var i = 0; i < values.length; i++)
{
//check to see if name and type are filled out - date is left off because length is "undefined"
if (values[i][0].length > 0)
{
//check if it's been entered before
if (values[i][13] == undefined)
{
//create event https://developers.google.com/apps-script/class_calendarapp#createEvent
var newEventTitle = values[i][0];
Logger.log(newEventTitle);
var dateStart = values[i][1];
var timeStart = values[i][2];
var dateFinish = values[i][3];
var timeFinish = values[i][4];
var startDateTime = new Date(dateStart+" "+timeStart);
startDateTime.setDate(startDateTime.getDate());
startDateTime.setMonth(startDateTime.getMonth());
startDateTime.setYear(startDateTime.getYear());
startDateTime.setTime(startDateTime.getTime());
var stopDateTime = new Date(dateFinish+" "+timeFinish);
stopDateTime.setDate(stopDateTime.getDate());
stopDateTime.setMonth(stopDateTime.getMonth());
stopDateTime.setYear(stopDateTime.getYear());
stopDateTime.setTime(stopDateTime.getTime());
var description = (values[i][7] == '' ? 'Test Description '+i : values[i][7]);
var location = (values[i][8] == '' ? 'Test Location '+i : values[i][8]);
Logger.log(description);
Logger.log(location);
//var newEvent = calendar.createAllDayEvent(newEventTitle, values[i][1]);
var newEvent = calendar.createEvent(newEventTitle, startDateTime, stopDateTime, {description:description,location:location});
//get ID
var newEventId = newEvent.getId();
//mark as entered, enter ID
sheet.getRange(i+2,14).setValue('y');
sheet.getRange(i+2,13).setValue(newEventId);
// in case of larger sheets we need to sleep the process
Utilities.sleep(1000);
}
else if (values[i][14] == 'u')
{
// can update event so need to delete and create again
// delete event
var event = calendar.getEventSeriesById(values[i][9]);
event.deleteEventSeries();
//create event
var newEventTitle = values[i][0];
//create event https://developers.google.com/apps-script/class_calendarapp#createEvent
var newEventTitle = values[i][0];
var dateStart = values[i][1];
var timeStart = values[i][2];
var dateFinish = values[i][3];
var timeFinish = values[i][4];
var startDateTime = new Date(dateStart+" "+timeStart);
startDateTime.setDate(startDateTime.getDate());
startDateTime.setMonth(startDateTime.getMonth());
startDateTime.setYear(startDateTime.getYear());
startDateTime.setTime(startDateTime.getTime());
var stopDateTime = new Date(dateFinish+" "+timeFinish);
stopDateTime.setDate(stopDateTime.getDate());
stopDateTime.setMonth(stopDateTime.getMonth());
stopDateTime.setYear(stopDateTime.getYear());
stopDateTime.setTime(stopDateTime.getTime());
var description = (values[i][7] == undefined ? 'Test Description '+i : values[i][7]);
var location = (values[i][8] == undefined ? 'Test Location '+i : values[i][8]);
//var newEvent = calendar.createAllDayEvent(newEventTitle, values[i][1]);
var newEvent = calendar.createEvent(newEventTitle, startDateTime, stopDateTime, {description:description,location:location});
//get ID
var newEventId = newEvent.getId();
//mark as entered, enter ID
sheet.getRange(i+2,14).setValue('y');
sheet.getRange(i+2,13).setValue(newEventId);
// in case of larger sheets we need to sleep the process
Utilities.sleep(1000);
}
else
{
Logger.log('I am groot');
sheet.getRange(i+2,14).setValue('y');
}
}
numValues++;
}
}
function onOpen()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
menuEntries.push({name: "Grades & Evals", functionName: "pushToCalendar"});
sheet.addMenu("Sync to Academic Master", menuEntries);
}
I found the issue finally .. one of those tiny issue found after logging more and googling the Invalid Date response.
On line 16 this
var values = range.getValues();
needed to change to this
var values = range.getDisplayValues();
So thanks :)
I figured out how to add an event to a calendar, but then spent a good 8 hours trying to figure out how to edit an existing event (or delete it, either way would get the job done). Here's what I've got:
function UpdateEventTime() {
var cal = CalendarApp.getCalendarById("semehjawioe#group.calendar.google.com");
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1; // First row of data to process
var numRows = 1; // Number of rows to process
var dataRange = sheet.getRange(startRow, 5, numRows, 5);
var data = dataRange.getValues();
// var oldtstart = SpreadsheetApp.getActiveSheet().getRange('G2');
// var oldtstop = SpreadsheetApp.getActiveSheet().getRange('H2');
// ??????????????????????????????????????????????????
// ?? How do I call up and delete the old event? ??
// ??????????????????????????????????????????????????
for (i in data) {
var row = data[i];
var title = row[0]; // First column
var desc = row[1]; // Second column
var tstart = row[2];
var tstop = row[3];
var loc = row[4];
cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
SpreadsheetApp.getActiveSheet().getRange('G2').setValue(tstart);
SpreadsheetApp.getActiveSheet().getRange('H2').setValue(tstop);
}
}
From what I can tell in the online documentation, you can't pull up an event, you can only pull up all the events in a date range. So at the end of the code I try to store the start time and stop time in a spreadsheet, and then refer back to it next time the script is executed. The commented out section in the middle is where I'm lost. That's where I'm trying to call up the event that I added last time I ran the script. I need to either edit it, or delete it.
Please help.
It would be better if you manage to save the event Ids in spreadsheet along with those details.
If you need to modify or delete those event, just fetch the event by id and do the things.
Modified code
For saving
var event = cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
var eventid = event.getId();
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(eventid);
To fetch the event back at later time
var id = SpreadsheetApp.getActiveSheet().getRange('I2');
var cal = CalendarApp.getCalendarById("semehjawioe#group.calendar.google.com");
var event = cal.getEventSeriesById(id);
//Now modify or delete the event
event.addEmailReminder(minutesBefore);
event.addGuest(email);
event.deleteEvent();
.
.
.
Hope this will help you
Here's a work in progress I put together. It still needs to be fined tuned, but I thought I would post it in case anyone has insight in optimizing the code, and for anyone that would find it useful. Basically the code creates an array from the calendar, and the spreadsheet, combines them. Sorts it on last modified (date last updated for event, and the standard scripted last modified column for spreadsheet), removes duplicates, and submits to both the calendar (currently after deleting all events) and the spreadsheet. I was planning on adding a key, and having a list where you would type the key to remove the items from both locations, the upside being you can add spreadsheet rows from calendar and vice versa. Thanks in advance for any helpful input.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Sync Spreadsheet to Calendar", functionName: "calsync"}];
//{name: “Sync”, functionName: “myimport”}];
ss.addMenu(“Calendar Sync”, menuEntries);
}
function calsync()
{
// This function should be executed from the
// spreadsheet you want to export to the calendar
var mySpreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“Test123″);
var myCalendar = CalendarApp.openByName(“Test”);
//calendar event array
var events = myCalendar.getEvents(new Date(“January 1, 2011 EST”),
new Date(“January 1, 2014 EST”));
if (events[0]) {
var eventarray = new Array();
var line = new Array();
line.push(‘Title’);
line.push(‘Start Date’);
line.push(‘End Date’);
line.push(‘Description’);
line.push(‘Last Modified’);
eventarray.push(line);
var i = 0;
for (i = 0; i < events.length; i++) {
line = new Array();
line.push(events[i].getTitle());
line.push(events[i].getStartTime());
line.push(events[i].getEndTime());
line.push(events[i].getDescription());
line.push(events[i].getLastUpdated());
//line.push(events[i].getLocation());
eventarray.push(line);
}
} else {
Browser.msgBox('nothing between ' + startDate + ' till ' + endDate);
}
var dataRange = mySpreadsheet.getRange("A2:E53");
var data = dataRange.getValues();
if (data[0]) {
var dataarray = new Array();
var line2 = new Array();
var j = 0;
for (j = 0; j < data.length; j++) {
var row = data[j];
line2 = new Array();
line2.push(row[0]);
line2.push(row[1]);
line2.push(row[2]);
line2.push(row[3]);
line2.push(row[4]);
//line.push(events[i].getLocation());
//line.push((events[i].getEndTime() – events[i].getStartTime()) / 3600000);
dataarray.push(line2);
}
} else {
Browser.msgBox('nothing between ' + startDate + ' till ' + endDate);
}
var newarray = eventarray.concat(dataarray);
uniquedata(newarray);
}
//found at https://developers.google.com/apps-script/articles/removing_duplicates
function uniquedata(data) {
var newData = new Array();
var data2 = sort(data, 4, false);
for(i in data2){
var row = data2[i];
var duplicate = false;
for(j in newData){
if(row[0] == newData[j][0]){
duplicate = true;
}
}
if(!duplicate){
newData.push(row);
}
}
var filtered = sort(newData, 4 , false);
UpdateSpreadsheet(filtered);
UpdateCalendar(filtered);
// var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test123");
// sheet.clearContents();
// sheet.getRange(1, 1, filtered.length, filtered[0].length).setValues(filtered);
}
function UpdateSpreadsheet(data) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test123");
sheet.clearContents();
sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}
function UpdateCalendar(data)
{
var myCalendar = CalendarApp.openByName("Test");
// optional – delete existing events
var events = myCalendar.getEvents(new Date("January 1, 2011 EST"),
new Date("January 1, 2013 EST"));
for (var i = 0; i 0) {
if (typeof columnIndex != “number” || columnIndex > data[0].length) {
throw ‘Choose a valide column index’;
}
var r = new Array();
var areDates = true;
for (var i = 0; i < data.length; i++) {
var date = new Date(data[i][columnIndex]);
if (isNaN(date.getYear()) && data[i][columnIndex] != '') areDates = false;
else if (data[i][columnIndex] != '') data[i][columnIndex] = date;
r.push(data[i]);
}
return r.sort(function (a, b) {
if (ascOrDesc) return ((a[columnIndex] b[columnIndex]) ? 1 : 0));
return ((a[columnIndex] > b[columnIndex]) ? -1 : ((a[columnIndex] < b[columnIndex]) ? 1 : 0));
});
}
else {
return data;
}
}
EDIT : I was writing my answer while Waqar was posting his answer... so it's kind of a repetition but I'll just post it so you get an example...
You can access events using their IDs, here is an example that adds guests to calendar events. It also updates a log sheet that shows the results.
function sendinvites(e) {
var ss = SpreadsheetApp.openById('0AnZ5_Sh________UJnVlFtNDM2NUE')
var sh = ss.getSheets()[0]
var logsheet = ss.getSheets()[1]
var last = ss.getLastRow();
var FUS1=new Date().toString().substr(25,8);
var calendar_name = 'test'
var group = GroupsManager.getGroup('groupemail');
var members = group.getAllMembers();
var startDate = new Date(e.parameter.start);
var endDate = new Date(e.parameter.end);
var Calendar = CalendarApp.getCalendarsByName(calendar_name);
var sheetName = calendar_name + "-du-" + Utilities.formatDate(e.parameter.start, FUS1, "dd-MMM-yyyy")
+ "-au-" + Utilities.formatDate(e.parameter.end, FUS1, "dd-MMM-yyyy")
//
var events = Calendar[0].getEvents(startDate , endDate);
if (events[0]) {
var eventarray = new Array();
var line = new Array();
line.push('Titre : '+calendar_name,'Début ','Fin','Localisation','Durée','invités');
eventarray.push(line);
for (i = 0; i < events.length; i++) {
var ID = events[i].getId()
var lr = logsheet.getLastRow();
logsheet.getRange(lr+1,1).setValue(events[i].getTitle()+' / '+Utilities.formatDate(events[i].getStartTime(), FUS1, "dd-MMM-yyyy"));
for(nn=0;nn<members.length;++nn){
logsheet.getRange(lr+1,nn+2).setValue(members[nn]);
Calendar[0].getEventSeriesById(ID).addGuest(members[nn])
}
line = new Array();
line.push(events[i].getTitle());
line.push(Utilities.formatDate(events[i].getStartTime(), FUS1, "dd-MMM-yyyy")+' à ' +Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm"));
line.push(Utilities.formatDate(events[i].getEndTime(), FUS1, "dd-MMM-yyyy")+' à ' +Utilities.formatDate(events[i].getEndTime(), FUS1, "HH:mm"));
line.push(events[i].getLocation());
line.push((events[i].getEndTime() - events[i].getStartTime()) / 3600000);
var invitelist='';
var list = Calendar[0].getEventSeriesById(ID).getGuestList()
for(nn=0;nn<list.length;++nn){invitelist+=list[nn].getName()+', '}
line.push(invitelist)
eventarray.push(line);
}
Logger.log(eventarray)
var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(sheetName);
sheet.getRange(1,1,eventarray.length,eventarray[0].length).setValues(eventarray);
sheet.getRange(1,1,1,eventarray[0].length).setBackgroundColor('#ffffcc');
sheet.setColumnWidth(1, 450);sheet.setColumnWidth(2, 150);sheet.setColumnWidth(3, 150);sheet.setColumnWidth(4, 250);sheet.setColumnWidth(5, 75);sheet.setColumnWidth(6, 450);;
sheet.setFrozenRows(1)
} else {
var startstring = Utilities.formatDate(e.parameter.start, FUS1, "dd-MMM-yyyy");
var endstring = Utilities.formatDate(e.parameter.end, FUS1, "dd-MMM-yyyy");
Browser.msgBox('Aucun événement entre le ' + startstring + ' et le ' + endstring +' dans votre agenda :'+calendar_name);
}
}
In case people are looking for this in the future, here's my final code after integrating Waqar's suggestions. It works. When it creates a new event, it grabs the eventID and stores it in the spreadsheet in cell I2. It "updates" existing events by finding the event based on that eventID, deleting it, and replacing it with a new one.
function CreateOrReplaceEvent() {
var cal = CalendarApp.getCalendarById("xxxxxxxxxxxxx#group.calendar.google.com");
var id = SpreadsheetApp.getActiveSheet().getRange('I2').getValue();
if(id != 0){
var event = cal.getEventSeriesById(id);
event.deleteEventSeries();
}
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1; // First row of data to process
var numRows = 1; // Number of rows to process
var dataRange = sheet.getRange(startRow, 5, numRows, 5);
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var title = row[0]; // First column
var desc = row[1]; // Second column
var tstart = row[2];
var tstop = row[3];
var loc = row[4];
var event = cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
var eventid = event.getId();
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(eventid);
}
}