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];
Related
I try to use a script from Create Google Calendar Events from Spreadsheet but prevent duplicates, however I can't make it work. It seems to me that there is a problem with the date format, though I use the standard one in my spreadsheet.
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 = "YOUR_CALENDAR_ID";
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[0]); // First column
var title = row[1]; // Second column
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[4];
var desc = row[5];
var id = row[6]; // 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(title, tstart, tstop, {description:desc,location:loc}).getId();
row[6] = newEvent; // Update the data array with event ID
}
else {
event.setTitle(title);
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);
}
Please, could you have a look what is wrong (my spreadsheet: https://docs.google.com/spreadsheets/d/1OIZLOjG5cg32EbV-bI5c2qDWtbhbggDTTobPK_dYfyQ/edit?usp=sharing). The script works but there is no result in my Google Calendar.
I thought that when I saw your showing script, date.getYear() might be required to be modified to date.getFullYear(). I thought that this might be the reason for your current issue of The script works but there is no result in my Google Calendar..
And, in your script, var date = new Date(row[0]), var tstart = new Date(row[2]) and var tstop = new Date(row[3]) might be written as var date = row[0], var tstart = row[2] and var tstop = row[3]. Because the cell values are the date object. So, how about the following modification?
From:
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
To:
var date = row[0];
var title = row[1];
var tstart = row[2];
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getFullYear());
var tstop = row[3];
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getFullYear());
Note:
In the case of var event = cal.getEventSeriesById(id);, I think that even when id is empty and the invalid value, no error occurs. So, try - catch might not be required to be used.
Reference:
getFullYear()
I have the below script and keep getting the error 'Cannot find method createEvent(number,string,string).' I can't figure out what's wrong. Any ideas?
function createCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow();
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
var data = dataRange.getValues();
var complete = "Done";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var aname = row[2]; //Agent
var cname = row[3]; //Client Name
var country = row[4]; //Client Country
var phone = row[5]; //Phone Number
var deposit = row[6]; //Type of Deposit
var ewallet = row[7]; //Processor/eWallet
var method = row[8]; //Deposit Method
var amount = row[9]; //Amount/Percent
var date = new Date(row[10]); //Date of Next Contact
var target = row[12]; //Target Amount
var history = row[13]; //Deposit History incl. dates
var currency = row[14]; //Currency
var comments = row[15]; //Comments
var stime = new Date (row[17]);
var etime = new Date (row[18]);
var added = row[19]; //Added to calendar
if (added != complete) {
var currentCell = sheet.getRange(startRow + i, numColumns);
var event = CalendarApp.getDefaultCalendar().createEvent(cname, stime, etime);
currentCell.setValue(complete)};
}
}
This error means that it cannot find that method, probably because you're using wrong arguments to the function createEvent(String,Date,Date) (see documentation here).
You are using function createEvent(number,String,String), which doesn't exist.
Your first variable cname should be transformed to string, and what you are also seing in the error is that 2nd and 3rd parameter are as string, while they should be dates.
The proper solution would be to transform starttime and endtime to date, and that depends on how is the format of your string date.
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.
Okay, first of all, what I'm trying to do is updating Google sheet and calendar simultaneously. So, let say if there's an update to your spreadsheet there will also be an update to the calendar. However, here's all the things that I failed to do.
If there's changes in the calendar , there will be no changes in the spreadsheet
I'm unable to find code to invite guest to the calendar. So far , all i know is that i need to to use " attendee[] " but I'm unable to find example to show me on how its done. I've found some java code but its different if I'm not mistaken.
So, these will be the order for the spreadsheet
Date Title Start Time End Time Location Description Guest EventID
This one is the code on the google sheets.
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Calendar Actions ", entries);
};
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1;
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "email"; // calenderID
var cal = CalendarApp.getCalendarById(calId);
for (i in data) {
if (i < headerRows) continue;
var row = data[i];
var date = new Date(row[0]);
var title = row[1];
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
tstart.setMinutes( tstart.getMinutes() + 6)
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
tstop.setMinutes(tstop.getMinutes() + 6)
var loc = row[4];
var desc = row[5];
var guest = row[6]
var id = row[7];
try
{
var event = cal.getEventSeriesById(id);
event.deleteEventSeries();
row[7] = '';
}
catch (e) {
}
var newEvent = cal.createEvent(title, new Date(tstart), new Date(tstop), {description:desc,location:loc}).getId();
row[7] = newEvent;
debugger;
}
range.setValues(data);
}
If possible , I would some guidance on this , since I'm stuck.
For this, if you want to create a new event for each new entry in spread sheet you could use Calender class and create an event.
If you want to edit an already created event and add new guests you could use CalendarEvent class and add guests.
Hope that helps!
I have attempted to create a google script that will create calendar events based on information within cells in google sheets. I have gotten to the point where everything is labeled and marked, but an error is occuring that states:
TypeError: Cannot find function createEvent in object Calendar. (line 18, file "Code")
Here is the code I have written:
function calInsert() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 25; // Number of rows to process
var dataRange = sheet.getRange(startRow, 2, numRows, 9);
var data = dataRange.getValues();
var cal = CalendarApp.getCalendarsByName( "EC Calendar" );
for (i in data) {
var row = data[i];
var title = row[1]; // First column
var tstart = row[2]; // Second column
var tstop = row[3];
var desc = row[4];
var loc = row[5];
var cmmail = row[6];
var leamail = row[7];
var event = cal.createEvent(title, new Date(tstart), new Date(tstop), {description:desc,location:loc,guests:cmmail,guests:leamail});
}
}
Any help you can provide would be appreciated.
var cal = CalendarApp.getCalendarsByName("EC Calendar");
This gives you an array of calendars with that name. Change this to:
var cal = CalendarApp.getCalendarsByName("EC Calendar")[0]; //Gets the correct calendar
This gives you the first Calendar with the name. I tried the below code:
function calInsert() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 5);
var data = dataRange.getValues();
var cal = CalendarApp.getCalendarsByName( "calendar ID" )[0];
for (i in data) {
var row = data[i];
var title = row[0]; // First column
var tstart = row[2]; // Second column
var tstop = row[3];
Logger.log(tstop);
var desc = row[1];
var loc = row[4];
//var cmmail = row[6];
//var leamail = row[7];
cal.createEvent(title, new Date(tstart), new Date(tstop), {description:desc,location:loc});
}
}
I am able to create event in my calendar. If needed, you can send cmmail and leamail to createEvent.