How to read a spreadsheet vertically - javascript

I am working in Google Scripts in combination with Google spreadsheets. The idea is that I make a spreadsheet that is able to read out events in a calendar. I am able to read to through the sheet horizontally, however I want to be able to read through it vertically.
See the script I have so far below.
function caltest1() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 23; // First row of data to process
var numRows = 2; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 10);
var data = dataRange.getValues();
var cal = CalendarApp.getDefaultCalendar();
for (i in data) {
var row = data[i];
var tstart = new Date(row[1]);
var tstop = new Date(row[7]);
var title = row[0]; // First column
var desc = row[2]; // Second column
var guest = row[8];
var loc = row[9];
cal.createEvent(title, tstart, { description: desc, location: loc, sendInvites: true, guests: guest });
}
}

Related

Create a checkbox in a cell when a other cell contains a date

I'm a noob to scripting and i have a spreadsheet that contains dates in some cells in row 0. Now i like te automatically create a checkbox in row 5 if row 0 contains a date. I use the checkbox to create or delete a event in the spreadsheet to a calendar. Now a need to put the check boxes in manually when i put in a new date.The script i'm using you can see down here.
spreadsheet i'm using
//**
// * Adds a custom menu to the active spreadsheet, containing a single menu item
// * for invoking the exportEvents() function.
// * The onOpen() function, when defined, is automatically invoked whenever the
// * spreadsheet is opened.
// * For more information on using the Spreadsheet API, see
// * https://developers.google.com/apps-script/service_spreadsheet
//*/
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Calendar Actions", entries);
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Delete Events",
functionName : "deleteAllDayEvents"
}];
sheet.addMenu("Delete events", entries);
};
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var space = " - "
var sheet = SpreadsheetApp.getActiveSheet();
//var sheetName = sheet.getName() als je een tweede sheet gebruikt
//if(sheetName != "Events"){
//return
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "stichtingmotardstein#gmail.com";
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
if(isNaN(date.valueOf()))
continue; // skip row, go to the next row
var numb = row[3];
var title = numb.substring(11,6) +space+ row[2];
var loc = row[1];
var id = row[4]; // 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.createAllDayEvent(title, date, {location:loc}).getId();
row[4] = newEvent; // Update the data array with event ID 4
}
else {
event.setTitle(title);
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, date);
}
debugger;
}
// Record all event IDs to spreadsheet
range.setValues(data);
}
function deleteAllDayEvents() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
var vA=rg.getValues();
var cal=CalendarApp.getCalendarById("stichtingmotardstein#gmail.com");
vA.forEach(function(r,i){
var id=r[4];
if(id && r[5]) {
cal.getEventById(id).deleteEvent();
sh.getRange(i+2,5).setValue("");
sh.getRange(i+2,6).setValue("TRUE");//just to reset the checkbox
}
})
}

CC section sending one email at a time, and then multiple to the first

so the below code in google appscript works fine except for the cc part which I just added, problem described after the code
function getSheetID(name){
var ss = SpreadsheetApp.getActive().getSheetByName(name)
var sheetID = ss.getSheetId().toString()
return sheetID
}
function DISCHEMEMAILS() {
//NEWEST PRODUCTS CODE
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DISCHEM LINES CHECK").activate();
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var shID = getSheetID("DISCHEM LINES CHECK") //Get Sheet ID of sheet name "DISCHEM LINES CHECK"
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID+"&gid="+shID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
//EMAIL ADDRESSES CODE FOR PRIMARY EMAIL
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DISCHEM EMAILS").activate();
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:B2
var dataRange = sheet.getRange(startRow,1,numRows,2);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = "Dear"+" "+row[1]+" "+"here are the classifications."; // Second column
var Sheets = [{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]
//EMAIL ADDRESSES CODE FOR BCC EMAIL
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DISCHEM EMAILS").activate();
var sheet = SpreadsheetApp.getActiveSheet();
var startRowcc = 3; // First row of data to process
var numRowscc = 5; // Number of rows to process
// Fetch the range of cells A3:B7
var dataRangecc = sheet.getRange(startRowcc,1,numRowscc,5);
// Fetch values for each row in the Range.
var datacc = dataRangecc.getValues();
for (var i2 in datacc) {
var rowcc = datacc[i2];
var emailAddresscc = rowcc[0]; // First column
MailApp.sendEmail({
to: emailAddress,
subject: "Classifications",
cc:emailAddresscc,
htmlBody: message,
attachments: Sheets
});
};
};
}
is having the effect of sending multiple emails for the cc instead of one with them together. It has three emails in the range, so it sends a email to me and email 1, then me and email 2, then three emails just to me.I want it to send one email, with email 1 and 2 ccd, and me as the primary.
Any ideas on what part of the formula I messed up? After testing some more I think it has to do with the positions of my }, but not sure where they should be
So I did a work around by referencing the cells directly with the emails in it instead of using the same code for the main email. Oh well it works now.
//cc emails
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DISCHEM EMAILS").activate();
var cc1 = SpreadsheetApp.getActiveSheet().getRange('A3').getValue();
var cc2 = SpreadsheetApp.getActiveSheet().getRange('A4').getValue();
//EMAIL ADDRESSES CODE FOR PRIMARY EMAIL
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DISCHEM EMAILS").activate();
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:B2
var dataRange = sheet.getRange(startRow,1,numRows,2);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = "Dear"+" "+row[1]+" "+"here are the classifications."; // Second column
var Sheets = [{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]
MailApp.sendEmail({
to: emailAddress,
subject: "Classifications",
htmlBody: message,
cc: cc1 + "," + cc2,
attachments: Sheets
});
};
}

How to get the cell values (Sheet1 from Google Form, Sheet2 from Formula) to google doc template

I have 2 sheets. Sheet1 is from Google Form and query them to Sheet2 then make the formula. I would like to get the cell values from them to Google Doc template and send the email. I can get values from Sheet1 but can't from Sheet2. Please help me solve this problem. Thank you.
enter image description here
enter image description here
function onFormSubmit(e){
var docs_email = e.values[1];
var Name = e.values[2];
var Date1 = e.values[3];
var Date2 = e.values[4];
var Money1 = e.values[5];
var Money2 = e.values[6];
//Values from Sheet2
var TotalDate = e.values[7];
var Money3 = e.values[8];
var TotalMoney = e.values[9];
var copyId = DriveApp.getFileById('Doc ID') //Temp document ID
.makeCopy('Report-'+Name)
.getId();
var copyDoc = DocumentApp.openById(copyId);
copyDoc.getBody()
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('keyName', Name);
copyBody.replaceText('keyDate1', Date1);
copyBody.replaceText('keyDate2', Date2);
copyBody.replaceText('keyMoney1', Money1);
copyBody.replaceText('keyMoney2', Money2);
copyBody.replaceText('keyTotalDate', TotalDate);
copyBody.replaceText('keyMoney3', Money3);
copyBody.replaceText('keyTotalMoney', TotalMoney);
copyDoc.saveAndClose();
//convert to pdf
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
//Send the email
var subject = "Your Report";
var body = "Dear " +Name+" \n\n"+"<br> This is your report";
GmailApp.sendEmail(docs_email, subject, body,{htmlBody: body, attachments: pdf});
}
How about this answer?
Modification points:
In order to retrieve the values from the columns "H" to "J" in "Sheet2", getValues is used.
From your question, I could understand that the columns "H" to "J" have the formula. So I thought that getLastRow() might not be able to be directly used. So I thought that it is required to retrieve the 1st empty row at the column "A".
When above points are reflected to your script, it becomes as follows.
Modified script:
Please modify your script as follows.
From:
var TotalDate = e.values[7];
var Money3 = e.values[8];
var TotalMoney = e.values[9];
To:
SpreadsheetApp.flush(); // This might be not required.
var sheet = e.source.getSheetByName("Sheet2"); // Values are retrieved from the sheet name of "Sheet2".
var row = 0;
for (var i = 1; i < sheet.getLastRow(); i++) {
if (sheet.getRange(i, 1).isBlank()) {
row = i - 1;
break;
}
}
var [TotalDate, Money3, TotalMoney] = sheet.getRange(row, 8, 1, 3).getValues()[0];
References:
getValues()
getSheetByName(name)
getLastRow()

Creating a Google Calendar Event from a spreadsheet "Cannot call method "setTitle of null."

I'm working on a script that generates a calendar event from a sheet in a google spreadsheet. after debugging the code I come up with no errors but when I run the code I get this "Cannot call method 'setTitle' of null". I have been unsuccessful in my attempts in troubleshooting and do not fully understand the substance of this error. Can someone help me understand what I'm doing wrong here?
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
ss.addMenu("Calendar Actions", entries);
};
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var headerRows = 389; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "somewhere#farfaraway.com";
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[11]); // column L
var title = row[9]; // Column J
var estimator = row[6];
var tstart = new Date(row[11]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[11]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[10]; // Column K
var desc = row[13]; // Column N
var id = row[0]; // Column A == eventId
// Check if event already exists, update it if it does
try {
var calev = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (estimator == "a person" && !calev) {
//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[0] = newEvent; // Update the data array with event ID
}
else {
calev.setTitle(title);
calev.setDescription(desc);
calev.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);
}

Trouble creating events in Google Agenda from Google Sheets with a script

I created a script in a Google Sheet to create events in Google Agenda, in order to study.
My goal is to create many events like this : if i study on D0, the first event must be at D+3, then D+10 , D+30, D+60.
I get many problems :
the script write "AJOUTE" in each box of the column (which means in french that the events are added to Agenda) , even if they are not completed with dates (I want to update for each chapter when it's done, and I do not do a whole chapter the same day!)
the script doesn't care if the events are already created, so i get multiple events for the same thing...
My script is the following :
var EVENT_IMPORTED = "AJOUTE";
var ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
var menuEntries = [{name: "Ajouter les événements à l'agenda", functionName: "importCalendar"}];
ss.addMenu("Agenda", menuEntries);
}
function importCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var startcolumn = 1
var numcolumns = 30
var dataRange = sheet.getRange(startcolumn, 1, numcolumns, 6)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var column = data[i];
var titre = column[1];
var DateJ3 = column[2];
var DateJ10 = column[3];
var DateJ30 = column[4];
var DateJ60 = column[5];
var eventImported = column[6];
var setupInfo = ss.getSheetByName("agenda");
var calendarName = setupInfo.getRange("A1").getValue();
if (eventImported != EVENT_IMPORTED && titre != "") {
var cal = CalendarApp.openByName(calendarName);
cal.createAllDayEvent(titre, new Date(DateJ3));
cal.createAllDayEvent(titre, new Date(DateJ10));
cal.createAllDayEvent(titre, new Date(DateJ30));
cal.createAllDayEvent(titre, new Date(DateJ60));
sheet.getRange(startcolumn + i, 7).setValue(EVENT_IMPORTED);
SpreadsheetApp.flush();
}
}
}
Thank you in advance, i'm despair, i searched for hours but found nothing to help...

Categories

Resources