How do I modify a google calendar event using google apps script? - google-apps-script

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);
}
}

Related

Create an array of values that were looped through

I have a spreadsheet where each row in "MASTER" sheet is a task. It has checkboxes to check if it's done.
On another sheet, "Sin despachar", the data is filtered so that only the tasks which are not done show. There I have empty checkboxes to check when an incomplete task is completed.
I wrote a script so that when a button is pressed, it loops through the whole column in "Sin despachar" to see if checkboxes are checked, and for those that are, it changes the value in a master sheet.
I would like to have a confirmation pop up that mentions all the tasks it'll edit, but for that I need to somehow retrieve that list when the script runs, and I don't know how.
So what I need is to create an array or something else that contains the names of the tasks with the checkbox checked.
Does anyone know how to do this?
The task names are in column 4, and the checkboxes are in column 18.
Thanks in advance!!
function marcarEtiquetado() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Sin despachar");
var sheetRange = s.getDataRange();
var sheetValues = sheetRange.getValues();
for (var i=sheetRange.getLastRow()-1; i>1; i--) {
// si valor en columna R (etiquetado) = TRUE
if ( sheetValues[i][17] === true) {
var checkboxRange = s.getRange(i, 18);
var usuariosRange = s.getRange(i, 3)
Logger.log(usuariosRange)
var targetSheet = ss.getSheetByName("*MASTER*");
var targetRow = sheetValues[i][1];
var targetRange = targetSheet.getRange( targetRow, 16);
var targetTS = targetSheet.getRange( targetRow, 17);
checkboxRange.setValue(false)
targetRange.setValue(true);
targetTS.setValue(new Date()).setNumberFormat("dd-mm-yy hh:mm")
} ;
}
s.getRange(3, 18, s.getLastRow()-2).setValue(false)
}
You use alerts to confirm for every checked box individually either and action shall be carried out.
Sample:
function marcarEtiquetado() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Sin despachar");
var sheetRange = s.getDataRange();
var sheetValues = sheetRange.getValues();
var ui = SpreadsheetApp.getUi();
for (var i=sheetRange.getLastRow()-1; i>1; i--) {
// si valor en columna R (etiquetado) = TRUE
if ( sheetValues[i][17] === true) {
var checkboxRange = s.getRange(i, 18);
var usuariosRange = s.getRange(i, 3)
var targetSheet = ss.getSheetByName("*MASTER*");
var targetRow = sheetValues[i][1];
var targetRange = targetSheet.getRange(targetRow, 16);
var targetTS = targetSheet.getRange(targetRow, 17);
var response = ui.alert('Do you want to set the timestamp for row ' + (i+1) + '?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (response == ui.Button.YES) {
checkboxRange.setValue(false)
targetRange.setValue(true);
SpreadsheetApp.getActiveSpreadsheet().toast("Timestamp will be set for row " + (i+1));
targetTS.setValue(new Date()).setNumberFormat("dd-mm-yy hh:mm")
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("Timestamp will not be set for row " + (i+1));
}
} ;
}
s.getRange(3, 18, s.getLastRow()-2).setValue(false)
}
If this is not what you wanted and you prefer to have a single confirmation dialog for all checked boxes, you can implement a help array and string as following:
function marcarEtiquetado2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Sin despachar");
var sheetRange = s.getDataRange();
var sheetValues = sheetRange.getValues();
var ui = SpreadsheetApp.getUi();
var rowKeeper = [];
var rowArray = ['\n'];
for (var i=sheetRange.getLastRow()-1; i>1; i--) {
// si valor en columna R (etiquetado) = TRUE
if ( sheetValues[i][17] === true) {
rowKeeper.push(i);
rowArray.push(i+1);
}
}
for (k = 0; k < rowArray.length-4; k += 5) {
rowArray[k+4] = rowArray[k+4] + "\n";
}
var rowString = rowArray.join(" ");
Logger.log(rowString);
var response = ui.alert('Do you want to set the timestamp for rows ' + rowString + '?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (response == ui.Button.YES) {
for (var j = 0; j < rowKeeper.length; j++){
var i = rowKeeper[j];
var checkboxRange = s.getRange(i, 18);
var usuariosRange = s.getRange(i, 3)
var targetSheet = ss.getSheetByName("*MASTER*");
var targetRow = sheetValues[i][1];
var targetRange = targetSheet.getRange(targetRow, 16);
var targetTS = targetSheet.getRange(targetRow, 17);
checkboxRange.setValue(false)
targetRange.setValue(true);
targetTS.setValue(new Date()).setNumberFormat("dd-mm-yy hh:mm")
}
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("No action will be carried out");
}
s.getRange(3, 18, s.getLastRow()-2).setValue(false)
}

Create Calendar event times from spreadsheet data for multiple time zones

I have created a basic Google sheet where staff will log meetings and then be able to export them to the google calendar.
The problem is that I have staff based in the US and in different timezones. I tried changing the spreadsheet settings but the timezones in Google seem a little unreliable (Pacific Time showing as GMT-8 when it is currently -7)...
I tried hardcoding the time difference as follows:
var tstart = new Date(tstart1.getTime() + 420 * 60000)
Now this works, except when it pushes the time past midnight. At this point it gets confused and states that end time must be later than start time. I guess therefore it is not pushing the date forward.
How can I stop this error occurring?
The rest of the code:
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Calendar Actions", entries);
};
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
// var calId = sheet.getRange("H2:H2").getValue();
var calId = "********";
var cal = CalendarApp.getCalendarById(calId);
for (i=0; i<data.length; i++) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[1]); // First column
var title = row[2]; // Second column
var initial = row[0];
var city = row[3];
var concatTitle = initial + " - " + title + ", " + city;
var tstart1 = new Date(row[4]);
var tstart = new Date(tstart1.getTime() + 420 * 60000)
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
//var tstop = new Date(row[4]);
var tstop = new Date(tstart.getTime() + row[5] * 60000);
// Logger.log(new Date(tstart.getTime() + 65 * 60000))
// var tstop = new Date(tstart + row[4]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[6];
var desc = row[7];
var id = row[8]; // Sixth column == eventId
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createEvent(concatTitle, tstart, tstop, {description:desc,location:loc}).getId();
row[8] = newEvent; // Update the data array with event ID
}
else {
event.setTitle(concatTitle);
event.setDescription(desc);
event.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
debugger;
}
// Record all event IDs to spreadsheet
range.setValues(data);
}

Event ID in wrong row, cannot call method deleteEvent

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.

google gs multiple calendars events to spreadsheet

attempting to extract all day events from Google calenders (three in total), into three sheadsheet pages each with two set of three column data. Max is about 100 rows in a month takeout. the entries are searchable by name event as well.
help, runs sort of okay, but gives me a time out, which may be to much information, also error pops up with getTitle not found.
anyone with suggestions to improve code and prevent time out, or any other suggestions to tidy up code would be of help. My thanks in advance.
This is what I have so far.
function export_gcal_to_gsheet() {
// This selects events only from calendars in date and list out
// Export Google Calendars Events to a Google Spreadsheet
// This code retrieves events between 2 dates for the specified calendar.
// It logs the results in the current spreadsheet starting at cell A6 listing the events,and date
// I do re-write the spreadsheet header in Row 6 with every run, as I found it faster to delete then entire sheet content,
// 1. Please modify the value for mycal to be YOUR calendar email address or one visible on your MY Calendars section of your Google Calendar
// 2. Please modify the values for events to be the date/time range you want and any search parameters to find or omit calendar entires
// Note: Events can be easily filtered out/deleted once exported from the calendar
// from an original file export_gcal_to_gsheet
// Reference Websites:
// https://developers.google.com/apps-script/reference/calendar/calendar
// https://developers.google.com/apps-script/reference/calendar/calendar-event
var mycal="";
var mySite="canv";
switch (mySite) {
case "canv" : mycal = "*****orqjiaaosl0dt0qp0g#group.calendar.google.com"; break;
case "salf" : mycal = "*****juiigo83ich4iga7sttlpa4#group.calendar.google.com"; break;
case "hart": mycal = "*****qblepqp88utr69vv434s#group.calendar.google.com"; break;
}//end switch
//var mycal = "*****hkdorqjiaaosl0dt0qp0g#group.calendar.google.com";
var cal = CalendarApp.getCalendarById(mycal);
// Optional variations on getEvents
// var events = cal.getEvents(new Date("January 3, 2014 00:00:00 CST"), new Date("January 14, 2014 23:59:59 CST"));
// var events = cal.getEvents(new Date("January 3, 2014 00:00:00 CST"), new Date("January 14, 2014 23:59:59 CST"), {search: 'word1'});
//
// Explanation of how the search section works (as it is NOT quite like most things Google) as part of the getEvents function:
// {search: 'word1'} Search for events with word1
// {search: '-word1'} Search for events without word1
var eventsbell = cal.getEvents(new Date("May 1, 2014 00:00:00 GMT"), new Date("May 10, 2014 23:59:59 GMT"), {search: 'bell'});
var eventspers = cal.getEvents(new Date("May 1, 2014 00:00:00 GMT"), new Date("May 2, 2014 23:59:59 GMT"), {search: 'pers'});
//var sheet = SpreadsheetApp.getActiveSheet();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mySite);
// Uncomment this next line if you want to always clear the spreadsheet content before running - Note people could have added extra columns on the data though that would be lost
sheet.clearContents();
// Create a header record on the current spreadsheet in cells A5:C5,E5:G5 - Match the number of entries in the "header=" to the last parameter
// of the getRange entry below
var header = [["Delivery Branch test", "Customer and Site test", "Delivery Date test"]]
var rangebell = sheet.getRange(5,1,1,3);
rangebell.setValues(header);
var rangepers = sheet.getRange(5,5,1,3);
rangepers.setValues(header);
// Loop through all calendar events found and write them out starting on calculated ROW 6 (i+6)
for (var i=0;i<eventsbell.length;i++) {
var row=i+6;
for (var i=0;i<eventspers.length;i++) {
var row=i+6;
// Matching the "header=" entry above, this is the detailed row entry "details=", and must match the number of entries of the GetRange entry below
var detailsbell = [[ mycal,eventsbell[i].getTitle(),eventsbell[i].getStartTime()]];
var rangebell = sheet.getRange(row,1,1,3);
rangebell.setValues(detailsbell);
var detailspers = [[ mycal,eventspers[i].getTitle(),eventspers[i].getStartTime()]];
var rangepers = sheet.getRange(row,5,1,3);
rangepers.setValues(detailspers);
}
}
}
I wrote such a script some time ago and use it all the time without issues. Here is a simplified version of it that you could try to see if it eventually works for you.
The code is a bit long but the operation is all but simple so I guess there is probably no way to make it really shorter.
I know that some methods used in this code are being deprecated (getTimeZone for example) but it will be easy to update when they become unavailable... for now it works as it is, I'll update when I get some time to do it.
Here is the link to a test sheet (in view only, make a copy to use)
var FUS1=new Date().toString().substr(25,6)+":00";
var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{name: "ImportCalendars", functionName: "Cal_to_sheetM"},
];
ss.addMenu("import cals", menuEntries);
}
function Cal_to_sheetM() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle("Import Calendars");
app.setHeight(365).setWidth(600);
// Create a grid with 3 text boxes and corresponding labels
var grid = app.createGrid(6, 2);
var wait = app.createImage('https://dl.dropboxusercontent.com/u/211279/loading3.gif').setVisible(false);
grid.setWidget(0, 0, app.createLabel("Cal Names :"));
var list = app.createListBox(true).setVisibleItemCount(5);
list.setName('calendar');
grid.setWidget(0, 1, list);
var calendars = CalendarApp.getAllCalendars();
for (var i = 0; i < calendars .length; i++) {
list.addItem(calendars[i].getName());
}
list.setItemSelected(0, true);
grid.setWidget(1, 0, app.createCheckBox("add cal Name to events").setName('addName').setValue(false))
.setWidget(2, 0, app.createLabel('start Date :'))
.setWidget(2, 1, app.createDateBox().setId("start").setValue(new Date(PropertiesService.getScriptProperties().getProperty('startDate'))))
.setWidget(3, 0, app.createLabel('End Date :'))
.setWidget(3, 1, app.createDateBox().setId("end").setValue(new Date(PropertiesService.getScriptProperties().getProperty('endDate'))))
.setWidget(4,0, app.createCheckBox("create new sheet").setName('newsheet').setValue(false));
var panel = app.createVerticalPanel();
panel.add(grid);
var button = app.createButton('Import');
var handler = app.createServerClickHandler('importEventsMulti');
handler.addCallbackElement(grid);
var cHandler = app.createClientHandler().forTargets(wait).setVisible(true).forEventSource().setEnabled(false);
button.addClickHandler(handler).addClickHandler(cHandler);
grid.setWidget(5, 1,button).setWidget(4,1, wait);
app.add(panel.add(grid));
doc.show(app);
}
function importEventsMulti(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var calendar_name = e.parameter.calendar.split(',');
var addName = e.parameter.addName=='true';
var newsheet = e.parameter.newsheet=='true';
var empty = ''
var startDate = new Date(e.parameter.start);
var endDate = new Date(e.parameter.end);
var sheetName = calendar_name.join('&');
if(newsheet){
try{
var sheet = ss.insertSheet(sheetName,0);
}catch(error){
FUS1=new Date().toString().substr(25,6)+":00";
var sheet = ss.insertSheet(sheetName+'-'+Utilities.formatDate(new Date(), FUS1, "HH:mm:ss"),0);
}
}else{
var allSheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sheetNames = '';
for(var s in allSheets){sheetNames+=allSheets[s].getName()};
if(sheetNames.indexOf(sheetName)>-1){
var newsheetName = sheetName+'-'+Utilities.formatDate(new Date(), FUS1, "HH:mm:ss")
}else{
var newsheetName = sheetName
}
var sheet = ss.getActiveSheet().setName(newsheetName);
}
var eventArray = new Array();
for(n=0;n<calendar_name.length;++n){
//Logger.log(calendar_name[n])
var Calendar = CalendarApp.getCalendarsByName(calendar_name[n]);
var events = Calendar[0].getEvents(startDate , endDate, {max: 4000});
if (events[0]){
for (i = 0; i < events.length; i++) {
var line = new Array();
FUS1=events[i].getStartTime().toString().substr(25,6)+":00";
var title = events[i].getTitle()
if(addName){title+=(' ('+calendar_name[n]+')')}
line.push(title);
line.push(Utilities.formatDate(events[i].getStartTime(), FUS1, "dd-MM-yyyy")+' # ' +Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm"));
line.push(Utilities.formatDate(events[i].getEndTime(), FUS1, "dd-MM-yyyy")+' # ' +Utilities.formatDate(events[i].getEndTime(), FUS1, "HH:mm"));
line.push(events[i].getLocation());
line.push(' -- ')
line.push(((events[i].getEndTime() - events[i].getStartTime())/ 3600000).toString().replace('.',','));
line.push(' ')
eventArray.push(line);
}
}else {
var startstring = Utilities.formatDate(e.parameter.start, FUS1, "dd-MM-yyyy");
var endstring = Utilities.formatDate(e.parameter.end, FUS1, "dd-MM-yyyy");
empty += calendar_name[n]+' - ';
}
}
if(empty.length>1){
Browser.msgBox('No events between ' + startstring + ' and ' + endstring +' in these calendars :'+empty);
}
//Logger.log(eventArray)
eventArray.sort(function(x,y){
var xp = new Date(x[1].substr(6,4)+'/'+x[1].substr(3,2)+'/'+x[1].substr(0,2)+' '+x[1].substr(13,2)+':'+x[1].substr(16,2)+':00').getTime();
var yp = new Date(y[1].substr(6,4)+'/'+y[1].substr(3,2)+'/'+y[1].substr(0,2)+' '+y[1].substr(13,2)+':'+y[1].substr(16,2)+':00').getTime();
return xp == yp ? 0 : xp > yp ? 1 : -1;
});
// now check for any double entry starting from the end
var eventArrayN = [];
var doublons = [];
for(i in eventArray){
var row = eventArray[i];
var duplicate = false;
for(j in eventArrayN){
if(row.join() == eventArrayN[j].join()){
duplicate = true;
}
}
if(!duplicate){
eventArrayN.push(row);
}else{
doublons.push(row);
}
}
var titre = ['calendars '+calendar_name.join(' + '),'starting ','ending','Ressources','--','duration','totals'];
eventArrayN.unshift(titre);
//Logger.log(eventArrayN.length);
// ss.setActiveSheet(ss.getSheets()[1]);
var lastRow = sheet.getLastRow();
sheet.getDataRange().clearContent().setBorder(false,false,false,false,false,false).setBackgroundColor('#ffffff')
sheet.getRange(1,1,eventArrayN.length,eventArrayN[0].length).setValues(eventArrayN);
sheet.setColumnWidth(1, 450).setColumnWidth(2, 150).setColumnWidth(3, 150).setColumnWidth(4, 250).setColumnWidth(5, 120).setColumnWidth(6, 75).setColumnWidth(7, 450);;
sheet.setFrozenRows(1)
sheet.getRange(1,1,1,eventArrayN[0].length).setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc').setFontWeight('bold').setHorizontalAlignment('center');
sheet.getRange('G' + (eventArrayN.length+1)).setValue('Total (global)').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
sheet.getRange('F' + (eventArrayN.length+1)).setFormula('=SUM(F2:F' + (eventArrayN.length)+ ')').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
var max = sheet.getMaxColumns();
var cstart = sheet.getLastColumn();
var n ;
for(n=max;n>cstart;--n){sheet.deleteColumn(n)}
var app = UiApp.getActiveApplication();
app.close();
if(doublons.length>0){
Browser.msgBox("There are duplicates in "+sheetName+", see log sheet");
var sheet = ss.insertSheet('LOG-'+Utilities.formatDate(new Date(), FUS1, "HH:mm:ss"),1);
Utilities.sleep(1500);
var titre = ['calendar : '+calendar_name.join(' + '),'start ','end','Ressources','--','Duration',' comments '];
doublons.unshift(titre);
sheet.getRange(1,1,doublons.length,doublons[0].length).setValues(doublons)
sheet.setColumnWidth(1, 450).setColumnWidth(2, 150).setColumnWidth(3, 150).setColumnWidth(4, 250).setColumnWidth(5, 120).setColumnWidth(6, 75).setColumnWidth(7, 450);;
sheet.setFrozenRows(1)
sheet.getRange(1,1,1,eventArrayN[0].length).setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc').setFontWeight('bold').setHorizontalAlignment('center');
sheet.getRange('G' + (eventArrayN.length+1)).setValue('Total global').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
sheet.getRange('F' + (eventArrayN.length+1)).setFormula('=SUM(F2:F' + (eventArrayN.length)+ ')').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
var max = sheet.getMaxColumns();
var cstart = sheet.getLastColumn();
var n ;
for(n=max;n>cstart;--n){sheet.deleteColumn(n)}
}
PropertiesService.getScriptProperties().setProperty('startDate',startDate);
PropertiesService.getScriptProperties().setProperty('endDate',endDate);
return app;
}

Google Apps for Business: Prevent users from reserving a resource for all-day events

My company has 15 rooms. Each room is a separate resource.
End-users are sometimes not very bright.
Sometimes they reserve a room for an all-day event, and nobody else can reserve the room for the entire day.
Which is why I want users to NOT be able to reserve a room for an all-day event, but instead specify time range.
Is there a way to do this with Google script?
I was thinking, one way to do this might be to have a script run every time an event is created. And if it its location is in one of the rooms, and it's an all-day event, delete it and prompt the user to try again.
So here's the problem--there doesn't seem to be a way to create a trigger which fires upon event creation.
I have had almost the same situation in the school I work in. We have about 20 classrooms and some of them have a shared access (as calendar ressources). The problem is that some endusers make use of this without caring about others and without telling anybody... so I made a 'tracking script' that runs every hours and checks if an event has been added to the ressource calendar; if it does, it sends me a mail so I can have a look and handle the situation.
After a few weeks, users became quite more careful on how they use the ressources since they know they are under surveillance ;-) so I don't need to delete the "bad events", they change it themselves !!
Anyway I guess the script I wrote could be modified quite easily to delete the events if they are "ALL DAY".
A few words to explain : the scripts keeps a log of all the events in a certain period of time (in ScriptProperties). Every hour or so it checks if some event has been added or removed, it checks also who did it and if it is not a "white listed" user it sends me an email with a summary of what changed (formatted in a HTML table). It monitors all events between now and a fixed date (for me end of June ).
The main difficulty I had was to handle the events dropping out of the list because of the date... in a first version it sent a mail on each event endTime...
Now this version is working smoothly for me for a couple of month and although it is not perfect it's probably a good starting point for you (at least I hope so :-)
There is also a manual logging utility to get all events in a spreadsheet between any start/end date and another utility to get the calendar ID's for the script.
Here is a public copy of the spreadsheet so you can have a look
here is the full script ( a bit long, sorry about that)
var nom = String(Session.getUser().getUserLoginId());
var authorized = ['admin','webmaster','mary','william'];// define a list of 'authorized event creators'
var owner = 'mail#xxx.yyy';// email to whom the email will be sent
var collaborator = 'a collaborator email';// email of an additional collaborator (optional, see line 93)
var ss = SpreadsheetApp.getActiveSpreadsheet();// this spreadsheet
var sh = ss.getSheetByName('master');
var calList = sh.getDataRange().getValues();
var logsheet = ss.getSheetByName('logger');
var last = logsheet.getLastRow();
var FUS1=new Date().toString().substr(25,6)+":00";
function onOpen() {
var menuEntries = [ {name: "Manual test", functionName: "checkCal"},
{name: "Lauch autoTest", functionName: "manualcheck"},
{name: "delete created sheets", functionName: "delsheets"}
];
var sheet = SpreadsheetApp.getActiveSpreadsheet();
sheet.addMenu("Tracking utilities",menuEntries);//
// Logger.log(FUS1)
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('logger'));// start on logger page
}
function manualcheck(){
autoCheckAllCals();
var sheet = SpreadsheetApp.getActiveSpreadsheet();
if(sheet.getSheets()>1){
SpreadsheetApp.setActiveSheet(sheet.getSheets()[2]);// this works from the menu when ss is open
}
}
function autoCheckAllCals(){
var eventarray = new Array();
var logarray = new Array();
var line = new Array();
ss.setActiveSheet(logsheet)
line.push('Events created by someone else','start ','end','location','Creator','Modification','event length','invited');
eventarray.push(line);
var today = new Date(); // maintenant
var startDate = new Date(today.getTime()-120*60*1000);// 2h before now
var endDate = new Date("june 30, 2013 23:59:00"); // choice every year
var sendMail = true
var mailSent = false
logsheet.insertRowAfter(last)
var sheetName = "Control from "+ Utilities.formatDate(startDate, FUS1, "MMM-dd-yy")
+ "-to-" + Utilities.formatDate(endDate, FUS1, "MMM-dd-yy")
for(nn=0;nn<calList.length;++nn){
var calName = calList[nn][0];
var calId = calList[nn][1];
// Logger.log(calList)
// Logger.log(startDate+' | '+endDate)
// Logger.log(calName+' | '+calId)
var Calendar = CalendarApp.getCalendarById(calId)
var events = Calendar.getEvents(startDate , endDate);
if (events[0]) {
for (var i = 0; i < events.length; i++) {
if(events[i].getTitle().match('week nr')=='week nr'){continue};// this condition to ignore week numbers that we add in all calendars.... might be anything else that should be ignored
var skip = false
for(var aaa in authorized){
//Logger.log(events[i].getCreators())
if(events[i].getCreators().join().match(authorized[aaa])==authorized[aaa]){skip=true;continue};// check if creator is in the 'authorized' list
}
if(skip){continue}
//Logger.log(events[i].getStartTime()+' '+events[i].getEndTime());
if(events[i].getStartTime()<today||events[i].getEndTime()<today){Logger.log('condition < today = true '
+events[i].getTitle()+' start='+Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm")+' end='+Utilities.formatDate(events[i].getEndTime(), FUS1, "HH:mm"));sendMail=false;continue}
// if condition = true update script properties so it won't generate an alert when finishing
var line = new Array();
var logline = new Array();
FUS1=events[i].getStartTime().toString().substr(25,6)+":00";
line.push(calName +' : '+events[i].getTitle());
logline.push(calName +' : '+events[i].getTitle()+'|');
line.push(Utilities.formatDate(events[i].getStartTime(), FUS1, "MMM-dd-yy")+' # ' +Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm"));
logline.push(Utilities.formatDate(events[i].getStartTime(), FUS1, "MMM-dd-yy")+' # ' +Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm")+'|');
line.push(Utilities.formatDate(events[i].getEndTime(), FUS1, "MMM-dd-yy")+' # ' +Utilities.formatDate(events[i].getEndTime(), FUS1, "HH:mm"));
line.push(events[i].getLocation());
line.push(events[i].getCreators().join());
logline.push(events[i].getCreators().join()+'∏');
line.push('on '+Utilities.formatDate(events[i].getLastUpdated(), FUS1, "MMM-dd-yy"))
line.push(((events[i].getEndTime() - events[i].getStartTime()) / 3600000)+' hours');
var invitelist='';
var list = events[i].getGuestList()
for(n=0;n<list.length;++n){invitelist+=list[n].getName()+', '}
line.push(invitelist)
eventarray.push(line);
logarray.push(logline)
}
// Logger.log(logarray)
}
}
if(eventarray.length>1){
var message = logarray.toString().replace(/,/g,'')
var formertest = ScriptProperties.getProperty('lastTest')
if(formertest!=message){
Logger.log('changement ...')
var html = createMsg(message)
if(sendMail){
MailApp.sendEmail(owner,'Events created by someone in your calendar', "", {"htmlBody" : html});
// MailApp.sendEmail(collaborator,'Events created by someone in your calendar', "", {"htmlBody" : html});// supprimer ou commenter cette ligne si nécessaire
Logger.log('send mail')
mailSent = true
}
ScriptProperties.setProperties({'lastTest': message}, true);
try{
var newsheet = ss.insertSheet(sheetName,2);
}catch(error){
FUS1=new Date().toString().substr(25,6)+":00";
var newsheet = ss.insertSheet(sheetName+' - '+Utilities.formatDate(new Date(), FUS1, "HH:mm:ss"),2);
}
newsheet.getRange(1,1,eventarray.length,eventarray[0].length).setValues(eventarray);
newsheet.getRange(1,1,1,eventarray[0].length).setBackgroundColor('#ffffcc');
newsheet.setColumnWidth(1, 350).setColumnWidth(2, 150).setColumnWidth(3, 150).setColumnWidth(4, 150).setColumnWidth(5, 150).setColumnWidth(6, 105).setColumnWidth(7, 95).setColumnWidth(8, 450);
newsheet.setFrozenRows(1)
}
ScriptProperties.setProperties({'lastTest': message}, true); // even if no mail, write to script properties
}
FUS1=new Date().toString().substr(25,6)+":00";
var logmsg = 'Auto test launched on '+Utilities.formatDate(new Date(), FUS1,"MMM-dd-yy # HH:mm");
if (mailSent){logmsg+=" - mail sent"}else{logmsg+=" - no alert"}
logsheet.getRange(last+1,1).setValue(logmsg);
}
function createMsg(logarray){
var formertest = ScriptProperties.getProperty('lastTest');
if(!formertest){return}
var testitems = formertest.split('∏');
var items = logarray.split('∏');
if(items.length>testitems.length){
var color='#CCFFCC'
if(testitems.toString().indexOf(items[0])==-1){color='#FFBBBB'}
var html = " Digest of Events created by someone else :<B> new events in RED </B><BR><BR><TABLE border = 1 cellpadding = 5><EVENTS></table>"
var table = "<tr valign='top' bgcolor='"+color+"' cellpadding=5>"
color='#CCFFCC'
for(zz=0;zz<items.length-1;++zz){
// Logger.log(testitems.toString().indexOf(items[zz]))
var subitems = items[zz].split('|')
if(testitems.toString().indexOf(items[zz+1])==-1){color='#FFBBBB'}
for(tt=0;tt<subitems.length;++tt){
table+= '<td>'+subitems[tt]+'</td>'
}
table+="</tr><tr valign='top' bgcolor='"+color+"' cellpadding=5>"
color='#CCFFCC'
}
table+='</tr>'
var msghtml = html.replace("<EVENTS>",table)
// Logger.log(msghtml)
return msghtml
}else{
var color='#FFBBBB'
if(items.toString().indexOf(testitems[0])==-1){color='#FFBBBB'}
var html = "One (or more) event removed <B>in RED</B> as shown below<BR><BR><TABLE border = 1 cellpadding = 5 bgcolor='"+color+"'><EVENTS></table>"
var table = "<tr valign='top' bgcolor='"+color+"' cellpadding=5>"
for(zz=0;zz<items.length;++zz){
// Logger.log(testitems.toString().indexOf(items[zz]))
var subitems = testitems[zz].split('|')
if(items.toString().indexOf(testitems[zz])==-1){
for(tt=0;tt<subitems.length;++tt){
table+= '<td>'+subitems[tt]+'</td>'
}
}
table+="</tr>"
}
table+='</tr>'
var msghtml = html.replace("<EVENTS>",table)
// Logger.log(msghtml)
return msghtml
}
}
function checkCalendars(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var calendar_name = e.parameter.calendar;
var startDate = new Date(e.parameter.start);
var endDate = new Date(e.parameter.end);
var calList = sh.getRange(1,1,sh.getLastRow(),2).getValues();
for(nn=0;nn<calList.length;++nn){
if(calList[nn][0]==calendar_name){var CalId = calList[nn][1];break}
}
var Calendar = CalendarApp.getCalendarById(CalId)
//
var sheetName = calendar_name + "-from-" + Utilities.formatDate(e.parameter.start, FUS1, "MMM-dd-yy")
+ "-to-" + Utilities.formatDate(e.parameter.end, FUS1, "MMM-dd-yy")
//
var events = Calendar.getEvents(startDate , endDate);
if (events[0]) {
logsheet.getRange(last+1,1).setValue('Manual test launched on '+Utilities.formatDate(new Date(), FUS1,"MMM-dd-yy"));
ss.setActiveSheet(logsheet)
var eventarray = new Array();
var line = new Array();
line.push('Calendar Name : '+calendar_name,'start ','end','Localisation','created by','Modification','event length','invited');
eventarray.push(line);
for (i = 0; i < events.length; i++) {
if(events[i].getTitle().match('week')=='week'){continue}
line = new Array();
line.push(events[i].getTitle());
FUS1=events[i].getStartTime().toString().substr(25,6)+":00";
line.push(Utilities.formatDate(events[i].getStartTime(), FUS1, "MMM-dd-yy")+' # ' +Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm"));
line.push(Utilities.formatDate(events[i].getEndTime(), FUS1, "MMM-dd-yy")+' # ' +Utilities.formatDate(events[i].getEndTime(), FUS1, "HH:mm"));
line.push(events[i].getLocation());
line.push(events[i].getCreators().join());
line.push('on '+Utilities.formatDate(events[i].getLastUpdated(), FUS1, "MMM-dd-yy"))
line.push((events[i].getEndTime() - events[i].getStartTime()) / 3600000);
var invitelist='';
var list = events[i].getGuestList()
for(nn=0;nn<list.length;++nn){invitelist+=list[nn].getName()+', '}
line.push(invitelist)
eventarray.push(line);
}
Logger.log(eventarray)
try{
var newsheet = ss.insertSheet(sheetName,2);
}catch(error){
var newsheet = ss.insertSheet(sheetName+'-'+Utilities.formatDate(new Date(), FUS1, "HH-mm-ss"),2)
}
newsheet.getRange(1,1,eventarray.length,eventarray[0].length).setValues(eventarray);
newsheet.getRange(1,1,1,eventarray[0].length).setBackgroundColor('#ffffcc');
newsheet.setColumnWidth(1, 350).setColumnWidth(2, 150).setColumnWidth(3, 150).setColumnWidth(4, 150).setColumnWidth(5, 150).setColumnWidth(6, 105).setColumnWidth(7, 95).setColumnWidth(8, 450);
newsheet.setFrozenRows(1)
SpreadsheetApp.setActiveSheet(sheet.getSheets()[2]);// envoie sur la page créée
} 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('no event between ' + startstring + ' and ' + endstring +' in your calendar :'+calendar_name);
}
var app = UiApp.getActiveApplication();
app.close();
return app;
}
function checkCal() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle("Calendar Tracking");
app.setHeight(265).setWidth(400);
// Create a grid with 3 text boxes and corresponding labels
var grid = app.createGrid(3, 2);
grid.setWidget(0, 0, app.createLabel("Name of the Calendar:"));
var list = app.createListBox();
list.setName('calendar');
grid.setWidget(0, 1, list);
for (var i = 0; i < calList.length; i++) {
list.addItem(calList[i][0]);
}
grid.setWidget(1, 0, app.createLabel('Start Date :'));
grid.setWidget(1, 1, app.createDateBox().setId("start").setValue(new Date()));
grid.setWidget(2, 0, app.createLabel('End Date :'));
grid.setWidget(2, 1, app.createDateBox().setId("end").setValue(new Date(new Date().getTime()+30*86400000)));
var panel = app.createVerticalPanel();
panel.add(grid);
var button = app.createButton('Start Checking & report');
var handler = app.createServerClickHandler('checkCalendars');
handler.addCallbackElement(grid);
button.addClickHandler(handler);
var clock = app.createImage('https://dl.dropbox.com/u/211279/Time-change-clock_animated_TR80.gif', 0, 0, 82, 82).setId('clock').setVisible(false);
var clockHandler = app.createClientHandler().forTargets(clock).setVisible(true);
button.addClickHandler(clockHandler)
panel.add(button).add(clock);
app.add(panel);
doc.show(app);
}
function delsheets(){
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
if(ss.getSheets()[pa].getSheetName()!='logger'&&ss.getSheets()[pa].getSheetName()!='master'){
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(400);
}
}
ss.setActiveSheet(ss.getSheets()[1]);// return to first sheet as active sheet (useful in 'list' function)
SpreadsheetApp.flush();
}
// This small function is to get the list of calendar names & Ids that you have access to, please edit the master sheet to keep only the ones you want to monitor (without empty rows).
function Callist(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('master')
sh.getDataRange().clearContent();
var list = new Array();
var store = new Array();
list = CalendarApp.getAllCalendars()
for (n=0;n<list.length;++n){
var name = list[n].getName() ;
var id = list[n].getId() ;
store.push( [name,id])
}
sh.getRange(1,1,store.length,store[0].length).setValues(store);
}