Cannot find function createEvent (or createAllDayEvent). (Google Spreadsheet App) - google-apps-script

here is my code that is causing the error. It seems to be just the line where I attempt to add the all day event. What needs to change to correct the error, or what does the error actually mean.
function SpreadsheetToCalendar3()
{
// This function should be executed from the
// spreadsheet you want to export to the calendar
var mySpreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My Calendar-Sheet01");
var myCalendar = CalendarApp.openByName("My Calendar-01");
// optional - delete existing events
var events = myCalendar.getEvents(new Date("November 1, 2018 EST"),
new Date("November 1, 2019 EST"));
for (var i = 0; i < events.length; i++)
{
events[i].deleteEvent();
}
var dataRange = mySpreadsheet.getRange("A2:B39");
var data = dataRange.getValues();
// process the data
for (i in data)
{
var row = data[i];
// assume that each row contains a date entry and a text entry
var theDate = row[1]; // First column of row
var theTitle = row[0]; // Second column of row
myCalendar.createAllDayEvent(theTitle, theDate);
}
}

Related

Date from Google Spreadsheet are shown one day behind in JSON

I have managed to write code to get the google spreadsheet data in JSON format. When I test the code in the script editor the dates show correctly but when I deployed and tested the link in postman.co all dates are one day behind. I mean it shows 31-Dec-2022 for 01-Jan-23, 01-Jan-23 for 02-Jan-23 and so on (one day earlier). I do not have time in the spreadsheet, by the way. How can I fix it?
Following is the script
function doGet(e) {
var records = {};
var rows = sheet.getRange(2, 1, sheet.getLastRow()-1, sheet.getLastColumn()).getValues();
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r], record = {};
record['Date'] = row[0];
record['Branch'] = row[1];
record['NetSale'] = row[2];
record['Profit'] = row[3];
data.push(record);
}
records.items = data;
// Logger.log(records)
var result = JSON.stringify(records);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}
Following is the screenshot of the Date column in the spreadsheet.

Calendar Events to Sheet is Duplicating - remove duplicates not working

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

AutoEmail based on Due date -_Reminder mail using google script

Snapshot of the google spreadsheet
function emailReminder() {
//For testing purposes
//You can view the log by typing CTRL+E after you run the script.
Logger.log(msg);
// grab the Google Sheet object
var googleSheets = SpreadsheetApp.getActiveSpreadsheet();
// activates the first sheet
SpreadsheetApp.setActiveSheet(googleSheets.getSheets()[0]);
// grabs the sheet
var currentSheet = googleSheets.getActiveSheet();
// find the last row
var lastRow = currentSheet.getLastRow();
// The first row starts at row 2 to account for headers
var startRow = 2;
// get E column data
var range = currentSheet.getRange(2,5,lastRow-startRow+1,1 );
var numRows = range.getNumRows();
var remainingDays = range.getValues();
// get A column data
range = currentSheet.getRange(2, 1, lastRow-startRow+1, 1);
var columnA = range.getValues();
// get D column data
range = currentSheet.getRange(2, 4, lastRow-startRow+1, 1);
var columnD = range.getValues();
var count = 0;
var msg = "";
// Loop column E
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft < 1) {
// Checks to see if a cell value in column E less than 1
var reminder = columnA[i][0];
**var reminderdate = columnD[i][0];**
msg = msg + "* Don't Forget: "+reminder+" is due on **"+reminderdate+"** which is "+daysLeft+" days.\n";
count++;
}
}
// Loop column E
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 1) {
// Checks to see if a cell value in column E equals 1
var reminder = columnA[i][0];
msg = msg + "Don't Forget: "+reminder+" is due tomorrow.\n";
count++;
}
}
// For multiple email addresses, use a comma to separate each email.
if(count) {
MailApp.sendEmail("yyy#gmai.com",
"Article Reminder", msg);
}
}
The output is coming in email as
Don't Forget:1231 is due onSun Feb 09 2020 00:00:00 GMT+0530
(India Standard Time) which is -67 days.
I want only the
Don't Forget:1231 is due on Sun Feb 09 2020 which is -67 days
to be reflecting in the output when the mail is sent.
Also, can the details be in table format which is not happening as of now when the mail is sent.(need to write the code for the same)
You can format the date you get from the Sheet so it only uses dd-MM-yyyy. To do so, use the Date() method and the Apps Script one Utitilies.formatDate.
For example:
var newDate = new Date(columnD[i][0]);
var reminder = Utilities.formatDate(newDate, "IST", "dd-MM-yyyy");
Then reminder will have the format like 11-Jan-2020.

Use array index to write value to different sheet row

I'm currently trying to get this piece of code to send events from a google sheet to a google calendar (Credit to Adam McFarland on this post).
My sheet is currently around 300 rows & growing so to speed things up I've set the range to start at row 248. But this then seems to throw off the part that notes the event as 'done'. It sets value of "In 2 calendar" to rows 2, 3, 4 & 5?!?
Easy solution would be just to set the range to the whole sheet again but I'm still learning. I'd like to learn what exactly here isn't working correctly, and also a bit more about how iteration works.
//mark as entered, enter ID
sheet.getRange(i+2, 32).setValue('In 2 calendar');
Complete code below:
function pushToCalendar() {
//spreadsheet variables
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var range = sheet.getRange(248,1,lastRow,40);
var values = range.getValues();
var updateRange = sheet.getRange('G1');
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) && (values[i][2].length > 0)) {
//check if it's been entered before
if (values[i][30] != 'In calendar') {
//Declare which calendar ID to use (IGNORE THIS FOR NOW)
var calendar = CalendarApp.getCalendarById('calendarID')
// if (values [i][3] != 'Tropical 2450 Pontoon'){
// var calendar = CalendarApp.getCalendarById('calendarID')
//create event https://developers.google.com/apps-script/class_calendarapp#createEvent
var newEventTitle = values[i][3]+'. '+values[i][2]+'. '+values[i][13]
+'. '+values[i][5]+'/'+values[i][6]+'/'+values[i][7]
+'. '+values[i][18]+' total, '+values[i][25]+' to pay. '+values[i][0];
// var newEvent = calendar.createEvent('hello', Date[i][1], Date[i][5]);
var newEvent = calendar.createEvent(newEventTitle,
//new Date(values[i][6]),
new Date(values[i][32]),
new Date(values[i][33]));
//{guests:'tures.com.au', sendInvites: true});
//mark as entered, enter ID
sheet.getRange(i+2, 32).setValue('In 2 calendar');
} //could edit here with an else statement
}
numValues++;
}
}

Troubleshooting script to amend Google Calendar from Google Sheets

I have a GAS script run from a Google Sheet with two functions. The first function downloads calendar event details in a named calendar between two dates. The name of the calendar, the start date and the end date are read in from cells A2, B2, and C2 respectively. This function is working fine:
//Function to list certain events in your GCalendar.
function listMyEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var calid = sheet.getRange("A2").getValue();
if(calid == null) {
SpreadsheetApp.getActiveSpreadsheet().toast('Please enter a valid calendar name!');
return;
}
var startTime = sheet.getRange("B2").getValue();
if(startTime == 0) {
SpreadsheetApp.getActiveSpreadsheet().toast('Please enter a start date!');
return;
}
if(isNaN(startTime)) {
SpreadsheetApp.getActiveSpreadsheet().toast('Please enter a valid start date!');
return;
}
var endTime = sheet.getRange("C2").getValue();
if(endTime == 0) { //If the cell doesn't contain anything send an error prompt
SpreadsheetApp.getActiveSpreadsheet().toast('Please enter an end date');
return;
}
if(isNaN(endTime)) { //If the cell holds text rather than a number then send an error prompt
SpreadsheetApp.getActiveSpreadsheet().toast('Please enter a valid end date!');
return;
}
var calendar = CalendarApp.getCalendarsByName(calid)[0]; //get the calendar name
var events = calendar.getEvents(startTime, endTime);
var data; //declare a variable to hold all the information.
for(var i = 0; i < events.length;i++){
var event = events[i];
data = [
event.getTitle(),
event.getDescription(),
event.getStartTime(),
event.getEndTime(),
event.getLocation(),
event.getId(),
"N"
];
sheet.appendRow(data);
}
sheet.autoResizeColumn(1);
sheet.autoResizeColumn(2);
sheet.autoResizeColumn(3);
sheet.autoResizeColumn(4);
sheet.autoResizeColumn(5);
sheet.autoResizeColumn(6);
sheet.autoResizeColumn(7);
}
The second function tries to read in the event Id from column F, in order to allow individual events to be amended within the sheet before being written back to Google Calendar. However, the script errors on the line calendarEvent.getId() with the error Cannot call method "getId" of undefined. (line 118, file "Code").
I did read that you need to use the .getEventSeriesById() method - but the events aren't in a series! Is it possible to amend individual events with a script or do I need to delete all events and recreate them with amendments? My code for the second function is here:
function amendCalEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 6; // First row of data to process
var numRows = sheet.getLastRow(); // Number of rows to process
//var maxRows = Math.min(numRows,200); //Limit the number of rows to prevent enormous number of event creations
var calid = sheet.getRange("A2").getValue(); //putting the calendar name in double quotes creates double entries. Who knew?
var dataRange = sheet.getRange(startRow, 1, numRows, 7); //startRow, startCol, endRow, endCol
var data = dataRange.getValues();
var cal = CalendarApp.getCalendarsByName(calid)[0]; //get the calendar name
for (i in data) {
var row = data[i];
var title = row[0]; // column A
var desc = row[1]; // column B
var tstart = row[2]; // column C
var tstop = row[3]; // column D
var loc = row[4]; // column E
var evId = row[5]; // column F
var evDelFlag = row[6]; // column G
var event = cal.calendarEvent.getId(evId);
if (evDelFlag == "N" || evDelFlag == "n") {
event.setTitle(title);
event.setDescription(desc);
event.setTime(tstart, tstop);
event.setLocation(loc);
} else {
cal.getId(evId).deleteEvent;
}
}
}
Any help or pointers are most gratefully accepted.
There are some changes you can do in the function amendCalEvents
1.- numRows variable, you are setting the value of getLasRow but you are not subtracting the rows used for the first information (e.g. if you have just 1 calendar and this calendar has one event, when you run the first function it'll add a new row and this variable will have 3 as value.
so when you u call the function getRange, it will bring the information from 3 rows and not just the one that has the information.
2.- a workaround of using the getEventSeriesById, you can probably call again the function getEvents as you did in the first fucntion.
As you are already looping in the for with a similar amount of data you could access the element inside the array o events and set the desired values.
var event = events[i];
3.- to delete the event now you can call:
event.deleteEvent();
Hope this helps