I am trying to write scirpt to add events from a spreadsheet to my google calendar. This is the script that I am using.
function addEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var cal = CalendarApp.getCalendarById("c_fe882662e583725f15fd4faa8c8fdf5124f3affe543778ecdcf0838d6eb17f26#group.calendar.google.com")
var data = ss.getRange("A3:D"+lr).getValues();
for(var i = 0;i<data.length;i++){
cal.createEvent(data[i][2],data[i][4],data[i][5],{location: data[i][6], description: data[i][7]});
}
}
When I run the script I am getting the following error. Error Exception: Invalid argument: startTime addEvents # Code.gs:10
This is the sheet that I am using with my dates.
https://docs.google.com/spreadsheets/d/1qG68-NLnq9LscPPzlnzRLCfHFIsN3v7V5zvWiVsG0qU/edit?usp=sharing
I want the title of the event to be column C, the start time to be Column E, the endtime to be Column F, Location G, and Description H.
Modification points:
In your script, in the for loop, data[i][4],data[i][5] is used as the start and end time. And also, data[i][7] is used. But, atvar data = ss.getRange("A3:D"+lr).getValues();, 4 columns of "A" to "D" are retrieved. I thought that this might be the reason for your issue. In this case, it is required to be var data = ss.getRange("A3:H" + lr).getValues().
But, when I saw your Spreadsheet, the start and end times don't have the year and month. In this case, 1899 year is used. Please be careful about this. From your Spreadsheet, I guessed that you might have wanted to use the year, month, and date from column "A".
When my understanding of your current issue and your goal, how about the following modification?
Modified script:
function addEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var cal = CalendarApp.getCalendarById("c_fe882662e583725f15fd4faa8c8fdf5124f3affe543778ecdcf0838d6eb17f26#group.calendar.google.com");
var data = ss.getRange("A3:I" + lr).getValues();
while (data[data.length - 1][0] == '') data.pop();
for (var i = 0; i < data.length; i++) {
var year = data[i][8].getFullYear();
var month = data[i][8].getMonth();
var date = data[i][8].getDate();
data[i][4].setFullYear(year);
data[i][4].setMonth(month);
data[i][4].setDate(date);
data[i][5].setFullYear(year);
data[i][5].setMonth(month);
data[i][5].setDate(date);
cal.createEvent(data[i][2], data[i][4], data[i][5], { location: data[i][6], description: data[i][7] });
}
}
When this script is run, the start and end times are retrieved from the columns "E" and "F", respectively. And also, the year, month, and date are retrieved from column "A". Using these values, the start and end date are created and they are used with createEvent.
When you want to use other values of year, month, and date instead of column "A", please tell me.
Note:
From your reply of This sounds promising, the sheet that I am using is actually setting up a mail merge as well and the date in column A is for the mail merge and not for the calendar. I would actually like column I to be the date for the calendar events. , I modified the above script.
From your reply of If I run this script twice (or multiple times) as I will continue to add events, it seems to duplicate the events that are already added. Any idea how to eliminate that?, I updated the above script as follows.
function addEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var cal = CalendarApp.getCalendarById("c_fe882662e583725f15fd4faa8c8fdf5124f3affe543778ecdcf0838d6eb17f26#group.calendar.google.com");
var data = ss.getRange("A3:R" + lr).getValues();
while (data[data.length - 1][0] == '') data.pop();
var rangeList = [];
for (var i = 0; i < data.length; i++) {
if (data[i][17] == "created") continue;
var year = data[i][8].getFullYear();
var month = data[i][8].getMonth();
var date = data[i][8].getDate();
data[i][4].setFullYear(year);
data[i][4].setMonth(month);
data[i][4].setDate(date);
data[i][5].setFullYear(year);
data[i][5].setMonth(month);
data[i][5].setDate(date);
cal.createEvent(data[i][2], data[i][4], data[i][5], { location: data[i][6], description: data[i][7] });
rangeList.push(`R${i + 3}`);
}
if (rangeList.length == 0) return;
ss.getRangeList(rangeList).setValue("created");
}
Try changing this: cal.createEvent(data[i][2],data[i][4],data[i][5],{location: data[i][6], description: data[i][7]}); to this cal.createEvent(data[i][2],new Date(data[i][4]),new Date(data[i][5]),{location: data[i][6], description: data[i][7]});
Try changing this var data = ss.getRange("A3:D"+lr).getValues(); to this var data = ss.getRange("A3:H"+lr).getValues();
Try this:
function addEvents() {
const ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var cal = CalendarApp.getCalendarById("jimesteban#jimesteban.com")
var data = sh.getRange("A3:H" + sh.getLastRow()).getValues();
for (var i = 0; i < data.length; i++) {
cal.createEvent(data[i][2], data[i][4], data[i][5], { location: data[i][6], description: data[i][7] });
}
}
Related
I created a spreadsheet for reporting students attendance that contains 8 sheets (each sheet named as a subject code). After completing a particular class, I go to the specific sheet (subject) and select all the rows of that particular date and press the button AfterClass-->Process Data (sorting, removing duplicates and protecting) using Google Apps Script/Macros. All working fine.
Now I created a DASHBOARD and I want that a teacher can do everything from the dashboard rather than going to individual sheet (subject). S/he can give two inputs - subject (sheetname) and Date from the Dashboard and then automatically process these specific dataset of that Sheet (Not all data of the sheet). Please note that date is in Column A and subject-code in Column F. The code I wrote as follows:
function AfterClass() {
var spreadsheet = SpreadsheetApp.getActive();
//Sorting and removing duplicates
var height = spreadsheet.getActiveSheet().getActiveRange().getHeight();
spreadsheet.getCurrentCell().offset(0, 0, height, 6).activate()
.sort({column: spreadsheet.getActiveRange().getColumn() + 2, ascending: true});
spreadsheet.getActiveRange().removeDuplicates([spreadsheet.getActiveRange().getColumn() + 2]).activate();
//Protecting data finally
//var lastRow = spreadsheet.getLastRow();
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var me = Session.getEffectiveUser();
var description = 'Protected on ' + stringDate + ' by ' + me;
var protection = SpreadsheetApp.getActiveSheet().getActiveRange().protect().setDescription(description);
//protection.setDomainEdit(false);
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
//Removing blank spacess in between data
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[1] == '') {
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
//For Double periods in a class
//var ss = SpreadsheetApp.getActiveSpreadsheet()
//var database = SpreadsheetApp.openById("xxx");
//var source = ss.getSheetByName('yyy');
var dataToCopyRng = SpreadsheetApp.getActiveSheet().getActiveRange(); //Gets range object of all data on source sheet
var dataToCopy = dataToCopyRng.getValues(); //Gets the values of the source range in a 2 dimensional array
var copyToSheet = SpreadsheetApp.getActiveSheet();
var copyData = copyToSheet.getRange(copyToSheet.getLastRow()+1,1,dataToCopy.length,dataToCopy[0].length).setValues(dataToCopy);
//Calculate class attendance and signed
var height2 = spreadsheet.getActiveSheet().getActiveRange().getHeight();
SpreadsheetApp.getActiveSheet().getCurrentCell().offset(2*height2,1).activate();
SpreadsheetApp.getActiveSheet().getCurrentCell().setRichTextValue(SpreadsheetApp.newRichTextValue()
.setText(height2 + ' Students, SIGNED')
.setTextStyle(0, 12, SpreadsheetApp.newTextStyle()
.setBold(true)
.build())
.build());
spreadsheet.getCurrentCell().offset(0, -1, 1, 6).activate();
spreadsheet.getActiveRangeList().setBackground('#e6b8af');
//.setBackground('#d9d9d9')
}
[dashboard][1]
[1]: https://i.stack.imgur.com/cMtHC.png
How to run your script from Dashboard after selecting the specified sheet and time
Modify your function in a way that it takes input from the cells A2 and C2 and D2 from Dashboard
Replace all instances of getActiveSheet() through getSheetByName(name), whereby name is your input from A1
Replace all instances of getActiveRange() through sheet.getRange(), whereby you define the range as as subrange as defined by the dates you retrieved
In order to find the first occurrence of the start date and the last occurrence of the end date - use the methods indexOf() and lastIndexOf()
Make sure that your date notation in Dashboard is the same as in the sheets for correct functionality
Sample:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('After Class')
.addItem('Process Data', 'AfterClass')
.addToUi();
}
function AfterClass() {
var spreadsheet = SpreadsheetApp.getActive();
var dashboard = spreadsheet.getSheetByName("Dashboard");
var sheetName = dashboard.getRange("A2").getValue();
//retrieve the start date to use as desired
var startDate = dashboard.getRange("C2").getDisplayValue();
var endDate = dashboard.getRange("D2").getDisplayValue();
var sheet = spreadsheet.getSheetByName(sheetName);
//chose the range within the specified dates, for this first locate the date column
var startRow = 2;
var dateColumn = sheet.getRange(startRow,1,sheet.getLastRow(), 1);
var dates = dateColumn.getDisplayValues().flat();
var firstRow = dates.indexOf(startDate)+startRow;
var lastRow = dates.lastIndexOf(endDate)+startRow;
//now get the range between (and including) those rows
var range = sheet.getRange(firstRow, 1, lastRow-firstRow+1, sheet.getLastColumn());
//Sorting and removing duplicates
// You need to specify by which column you want to sort your data, in this sample it it column 3 - that it column C
var column = 3;
range.sort({column: column, ascending:true});
range.removeDuplicates([column]);
//now delete empty rows if any
for (var i = range.getHeight(); i >= 1; i--){
if(range.getCell(i, 1).isBlank()){
sheet.deleteRow(range.getCell(i, 1).getRow());
}
}
//Protecting data
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var me = Session.getEffectiveUser();
var description = 'Protected on ' + stringDate + ' by ' + me;
var protection = range.protect().setDescription(description)
//protection.setDomainEdit(false);
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}
Important
The sample above will work if your sheet is sorted by dates (ascending) - as you specified in the comments. However, once the data is sorted by column C and not dates anymore it might not work as intended.
Sidenote:
From your code I understand that you recorded it as a macro rather than writing it from scratch (visible by the (unnecessary) calls of activate()).
I very much recommend you to take some time to study Apps Script in roder to understand your code in depth and be able to perform modificaitons and adjustments according to your needs.
There is the basic tutorial for Apps Script in general, samples and explanations for Google Sheets in specific and the references for all available Apps Script methods, whereby most methods feature a code sample.
I have searched many possible answers but cannot seem to find one that works. I have a Google Sheet with about 1600 rows that I need to split into about 70 different tabs (with about 20-30 rows in each one) based on the value in the column titled “room”. I have been sorting and then cutting and pasting but for 70+ tabs this is very tedious.
I can use the Query function but I still need to create a new tab, paste the function and update the parameter for that particular tab.
This script seemed pretty close:
ss = SpreadsheetApp.getActiveSpreadsheet();
itemName = 0;
itemDescription = 1;
image = 2;
purchasedBy = 3;
cost = 4;
room = 5;
isSharing = 6;
masterSheetName = "Master";
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Update Purchases')
.addItem('Add All Rows To Sheets', 'addAllRowsToSheets')
.addItem('Add Current Row To Sheet', 'addRowToNewSheet')
.addToUi();
}
function addRowToNewSheet() {
var s = ss.getActiveSheet();
var cell = s.getActiveCell();
var rowId = cell.getRow();
var range = s.getRange(rowId, 1, 1, s.getLastColumn());
var values = range.getValues()[0];
var roomName = values[room];
appendDataToSheet(s, rowId, values, roomName);
}
function addAllRowsToSheets(){
var s = ss.getActiveSheet();
var dataValues = s.getRange(2, 1, s.getLastRow()-1, s.getLastColumn()).getValues();
for(var i = 0; i < dataValues.length; i++){
var values = dataValues[i];
var rowId = 2 + i;
var roomName = values[room];
try{
appendDataToSheet(s, rowId, values, roomName);
}catch(err){};
}
}
function appendDataToSheet(s, rowId, data, roomName){
if(s.getName() != masterSheetName){
throw new Error("Can only add rows from 'Master' sheet - make sure sheet name is 'Master'");
}
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
var roomSheet;
if(sheetNames.indexOf(roomName) > -1){
roomSheet = ss.getSheetByName(roomName);
var rowIdValues = roomSheet.getRange(2, 1, roomSheet.getLastRow()-1, 1).getValues();
for(var i = 0; i < rowIdValues.length; i++){
if(rowIdValues[i] == rowId){
throw new Error( data[itemName] + " from row " + rowId + " already exists in sheet " + roomName + ".");
return;
}
}
}else{
roomSheet = ss.insertSheet(roomName);
var numCols = s.getLastColumn();
roomSheet.getRange(1, 1).setValue("Row Id");
s.getRange(1, 1, 1, numCols).copyValuesToRange(roomSheet, 2, numCols+1, 1, 1);
}
var rowIdArray = [rowId];
var updatedArray = rowIdArray.concat(data);
roomSheet.appendRow(updatedArray);
}
But I always get an unexpected token error on line 51 or 52:
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
(And obviously the column names, etc. are not necessarily correct for my data, I tried changing them to match what I needed. Not sure if that was part of the issue.)
Here is a sample of my data: https://docs.google.com/spreadsheets/d/1kpD88_wEA5YFh5DMMkubsTnFHeNxRQL-njd9Mv-C_lc/edit?usp=sharing
This should return two separate tabs/sheets based on room .
I am obviously not a programmer and do not know Visual Basic or Java or anything. I just know how to google and copy things....amazingly I often get it to work.
Let me know what else you need if you can help.
Try the below code:
'splitSheetIntoTabs' will split your master sheet in to separate sheets of 30 rows each. It will copy only the content not the background colors etc.
'deleteTabsOtherThanMaster' will revert the change done by 'splitSheetIntoTabs'. This function will help to revert the changes done by splitSheetIntoTabs.
function splitSheetIntoTabs() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var header = rows[0];
var contents = rows.slice(1);
var totalRowsPerSheet = 30; // This value will change no of rows per sheet
//below we are chunking the toltal row we have into 30 rows each
var contentRowsPerSheet = contents.map( function(e,i){
return i%totalRowsPerSheet===0 ? contents.slice(i,i+totalRowsPerSheet) : null;
}).filter(function(e){ return e; });
contentRowsPerSheet.forEach(function(e){
//crate new sheet here
var currSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
//append the header
currSheet.appendRow(header);
//populate the rows
e.forEach(function(val){
currSheet.appendRow(val);
});
});
}
// use this function revert the sheets create by splitSheetIntoTabs()
function deleteTabsOtherThanMaster() {
var sheetNotToDelete ='Master';
var ss = SpreadsheetApp.getActive();
ss.getSheets().forEach(function(sheet){
if(sheet.getSheetName()!== sheetNotToDelete)
{
ss.deleteSheet(sheet);
}
});
}
I was using Kessy's nice script, but started having trouble when the data became very large, where the script timed out. I started looking for ways to reduce the amount of times the script read/wrote to the spreadsheet (rather than read/write one row at a time) and found this post https://stackoverflow.com/a/42633934
Using this principle and changing the loop in the script to have a loop within the loop helped reduce these calls. This means you can also avoid the second call to append rows (the "else"). My script is a little different to the examples, but basically ends something like:
`for (var i = 1; i < theEmails.length; i++) {
//Ignore blank Emails and sheets created
if (theEmails[i][0] !== "" && !completedSheets.includes(theEmails[i][0])) {
//Set the Sheet name = email address. Index the sheets so they appear last.
var currentSheet = theWorkbook.insertSheet(theEmails[i][0],4+i);
//append the header
//To avoid pasting formulas, we have to paste contents
headerFormat.copyTo(currentSheet.getRange(1,1),{contentsOnly:true});
//Now here find all the rows containing the same email address and append them
var theNewRows =[];
var b=0;
for(var j = 1; j < rows.length; j++)
{
if(rows[j][0] == theEmails[i][0]) {
theNewRows[b]=[];//Initial new array
theNewRows[b].push(rows[j][0],rows[j][1],rows[j][2],rows[j][3],rows[j][4],rows[j][5],rows[j][6],rows[j][7]);
b++;
}
}var outrng = currentSheet.getRange(2,1,theNewRows.length,8); //Make the output range the same size as the output array
outrng.setValues(theNewRows);
I found a table of ~1000 rows timed out, but with the new script took 6.5 secs. It might not be very neat, as I only dabble in script, but perhaps it helps.
I have done this script that successfully gets each room and creates a new sheet with the corresponding room name and adding all the rows with the same room.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
// This var will contain all the values from column C -> Room
var columnRoom = sheet.getRange("C:C").getValues();
// This var will contain all the rows
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
//Set the first row as the header
var header = rows[0];
//Store the rooms already created
var completedRooms = []
//The last created room
var last = columnRoom[1][0]
for (var i = 1; i < columnRoom.length; i++) {
//Check if the room is already done, if not go in and create the sheet
if(!completedRooms.includes(columnRoom[i][0])) {
//Set the Sheet name = room (except if there is no name, then = No Room)
if (columnRoom[i][0] === "") {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("No Room");
} else {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(columnRoom[i][0]);
}
//append the header
currentSheet.appendRow(header);
currentSheet.appendRow(rows[i]);
completedRooms.push(columnRoom[i][0])
last = columnRoom[i][0]
} else if (last == columnRoom[i][0]) {
// If the room's sheet is created append the row to the sheet
var currentSheet = SpreadsheetApp.getActiveSpreadsheet()
currentSheet.appendRow(rows[i]);
}
}
}
Please test it and don't hesitate to comment for improvements.
I have a Google spreadsheet that we're using to deliver single calendar events to multiple accounts. Code below. I am getting an "Invalid argument" error for .addguest whenever there is more than one email address in the cell I'm trying to pull from (separated by commas).
The code below will pull correctly if only one account is in the cell, but not if multiple accounts are listed with commas in that same cell.
All ideas appreciated.
Thank you!
--Drew
function onOpen() {
var s = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Add Events to Google Calendar", functionName: "scheduleClass"}];
s.addMenu("Google Calendar Functions", menuEntries);
}
function scheduleClass(){
var sheet = SpreadsheetApp.getActiveSheet();
var calendar = CalendarApp.getCalendarById("primary#group.calendar.google.com");
var title = sheet.getRange('A2:A').getValues();
var startTime = sheet.getRange('E2:E').getValues();
var endTime = sheet.getRange('F2:F').getValues();
var theDescription = sheet.getRange('G2:G').getValues();
var theLocation = sheet.getRange('H2:H').getValues();
var theGuests = sheet.getRange('K2:K').getValues();
for(var i = 0; i < title.length+1; i++){
if(title[i][0] != ""){
calendar.createEvent(title[i][0], startTime[i][0], endTime[i][0]).addGuest(theGuests[i][0]).setLocation(theLocation[i][0]).setDescription(theDescription[i][0]);
}
}
}
function toString(value){
var newString = "" + value;
return newString;
}
You want to create the calendar events with the multiple guests.
In your situation, the value of column "K" is like sample1#gmail.com,sample2#gmail.com which is separated by ,.
The values of columns "A", "E", "F", "G", "H" and "K" in the active sheet are title, start time, end time, description, location and guests, respectively.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
When the guests are separated by ,, you can retrieve each email using split(). And they can be added with addGuest(email).
In your script, an error occurs at the loop by title.length+1 of for(var i = 0; i < title.length+1; i++){.
When you retrieve the values from the data range of "A2:K#", the process cost can be reduced. This was mentioned by Cooper's comment and discussions.
When these points are reflected to your script, it becomes as follows.
Pattern 1:
In this pattern, the calendar service of CalendarApp is used. In this case, scheduleClass() was modified.
Modified script:
function scheduleClass(){
var sheet = SpreadsheetApp.getActiveSheet();
var calendar = CalendarApp.getCalendarById("primary#group.calendar.google.com");
var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 11).getValues();
for(var i = 0; i < values.length; i++){
var [title,,,,startTime,endTime,theDescription,theLocation,,,theGuests] = values[i];
if(title != "") {
var event = calendar.createEvent(title, startTime, endTime)
.setLocation(theLocation)
.setDescription(theDescription);
theGuests.split(",").forEach(function(e) {event.addGuest(e.trim())});
}
}
}
Pattern 2:
In this pattern, Calendar API is used.
Modified script:
When you use this script, please enable Calendar API at Advanced Google services.
function scheduleClass(){
var sheet = SpreadsheetApp.getActiveSheet();
var calendarId = "primary#group.calendar.google.com";
var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 11).getValues();
for(var i = 0; i < values.length; i++){
var [title,,,,startTime,endTime,theDescription,theLocation,,,theGuests] = values[i];
if(title != "") {
var resource = {
start: {dateTime: startTime.toISOString()},
end: {dateTime: endTime.toISOString()},
summary: title,
description: theDescription,
location: theLocation,
attendees: theGuests.split(",").map(function(e) {return {email: e.trim()}})
};
Calendar.Events.insert(resource, calendarId);
}
}
}
Note:
Above both modified scripts are the same results.
References:
split()
forEach()
map()
addGuest(email)
Advanced Google services
Events: insert
If I misunderstood your question and this was not the direction you want, I apologize.
I'm currently working on creating a Google Sheet that would allow me to create calendar events (reminders) for when certain reports are due for me.
Basically, on the basis of a given opening date, I have 5 different types of reports due, some at different intervals (ie, 45 days from the open date, 6 months, 12 months). I've been able to modify a sample I found online (http://www.adammcfarland.com/2013/08/09/tutorial-using-google-spreadsheets-to-update-a-google-calendar-our-new-vacation-management-system/), customizing a Google Sheet to generate due dates for each type of report, and create calendar entries based on those due dates. It's actually really cool and powerful.
Unfortunately, I'm stumbling when it comes to creating notifications for the different reports. I know how to create default notifications within the Google Calendar interface, but the quirk I'm currently trying to address is that of these various reports, not all require as much time to complete, so I'm looking to create notifications specific to each report type, and I'm thus far been wholly unable to get things working.
Here's a copy of the script I'm using.
enter code herefunction pushToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var range = sheet.getRange(2,1,lastRow,5);
var values = range.getValues();
var updateRange = sheet.getRange('G1');
var calendar = CalendarApp.getCalendarById('jk.com_5e9gk4#group.calendar.google.com')
updateRange.setFontColor('red');
var numValues = 0;
for (var i = 0; i < values.length; i++) {
if ((values[i][0].length > 0) && (values[i][2].length > 0)) {
if (values[i][3] != 'y') {
var newEventTitle = 'Note Due: ' + values[i][0] + ' - ' + values[i][2];
var newEvent = calendar.createAllDayEvent(newEventTitle, values[i][1]);
var newEventId = newEvent.getId();
sheet.getRange(i+2,4).setValue('y');
sheet.getRange(i+2,5).setValue(newEventId);
}
Where "values[i][2]" corresponds to the type of report due.
Thanks in advance.
You can try to addreminder just after creating event based on a table. See the code below :
function pushToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
//Define reminder, value in minute and lower 4weeks (=40320 minutes)
var reminder = {"type1":1440,//=1 day
"type2":7200,//5days
"type3":20160//2weeks
};
//End define reminder
var lastRow = sheet.getLastRow();
var range = sheet.getRange(2,1,lastRow,5);
var values = range.getValues();
var updateRange = sheet.getRange('G1');
var calendar = CalendarApp.getCalendarById('jk.com_5e9gk4#group.calendar.google.com')
updateRange.setFontColor('red');
var numValues = 0;
for (var i = 0; i < values.length; i++) {
if ((values[i][0].length > 0) && (values[i][2].length > 0)) {
if (values[i][3] != 'y') {
var newEventTitle = 'Note Due: ' + values[i][0] + ' - ' + values[i][2];
var newEvent = calendar.createAllDayEvent(newEventTitle, values[i][1]);
//Add reminder
//For that we assume you well created the reminder var and all type have the amount of minutes define if not you must implement the check in he code
newEvent.addEmailReminder(reminder[values[i][2]]);
//End add reminder
var newEventId = newEvent.getId();
sheet.getRange(i+2,4).setValue('y');
sheet.getRange(i+2,5).setValue(newEventId);
}
}
}
}
I added some comments in the code for you.
Stéphane
I am working in a google document spreadsheet to make a list of active customers. I am attempting to create a script that when a completion date is entered, that row (all the customer info) is transfered to another sheet and/or deleted. I started a script but it isn't working properly.
function myFunction() {
'var ssdate = spreadsheet.column B'
// the "if" clause : if (date = 1) {
// the "then" clause : then ( move row to sheet 2)
}
Since this is my first time, I am sure this needs some work, but any help would be greatly appreciated.
It's much easier to read the Google Apps Script tutorials and guide first. They will give you a much better quick start.
Please try the following example:
var ddate = Utilities.formatDate(new Date(), "GMT", "MM-dd-yy");
function checkDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var rows = sheet.getDataRange();
var rowsNumber = rows.getNumRows();
var column = sheet.getDataRange();
var values = column.getValues();
for (var i = 1; i <= rowsNumber -1; i++){
var customerData = values[i];
var customerDate = customerData[2];
var myRow = Math.round(i) +1;
var conCustomerDate = Utilities.formatDate(new Date(customerDate), "GMT", "MM-dd-yy");
if (conCustomerDate > ddate){
sheet.getRange("D" + myRow).setValue("OK");
}
else {
sheet.getRange("D" + myRow).setValue("Old");
}
}
}