I've been trying to code a function for a Google form that will send an email to a particular teacher that is indicated by the form. The problem is that I keep getting an error on a simple if statement. The error says, "Missing ; before statement. (line 29, file "Code")". The code is based on this Google Apps tutorial: https://developers.google.com/apps-script/articles/mail_merge#section-5-full-code. This is what I have right now:
function sendEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheets()[0];
var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 4);
var templateSheet = ss.getSheets()[1];
var emailTemplate = templateSheet.getRange("A1").getValue();
// Create one JavaScript object per row of data.
var objects = getRowsData(dataSheet, dataRange);
// For every row object, create a personalized email from a template and send
// it to the appropriate person.
for (var i = 0; i < objects.length; ++i) {
// Get a row object
var rowData = objects[i];
// Generate a personalized email.
// Given a template string, replace markers (for instance ${"First Name"}) with
// the corresponding value in a row object (for instance rowData.firstName).
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
var emailSubject = "Lab Visit Report";
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
var teacher = data[i][10];
If (teacher == "Jake Nabasny") {MailApp.sendEmail("JakeN#school.edu", emailSubject, emailText);}
else if (teacher == "Dan S") {MailApp.sendEmail("DanS#school.edu", emailSubject, emailText);}
}
}
I've already made sure that the variables (such as teacher and emailText) contain data. The problem, as far as I can tell, is solely with the if statement. Can anyone please give me an idea of what is going wrong here?
You seem to have capitialised an If ...
Related
I want to access simply the 2nd tab to get email and name values to be used to send automated emails. Currently, the code is using the first tab. Additionally, how do I specify that it should take only rows (on the second tab) which have values instead of taking the entire column with many blanks which then throw errors?
function sendemail() {
var spreadSheet = SpreadsheetApp.getActiveSheet();
var dataRange = spreadSheet.getDataRange();
var data = dataRange.getValues();
for (var i = 1; i < data.length; i++) {
(function(val) {
var row = data[i];
var emailAddress = row[1]; //position of email header — 1
var message = 'Hi There!';
var subject = 'Test';
MailApp.sendEmail(emailAddress, subject, message);
})(i);
}
}
To get the second sheet / tab in a Spreadsheet you can use the getSheets method and take the second element of the returned list of Sheets:
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var secondSheet = sheets[1];
To retrieve only populated rows use the getDataRange method to retrieve the Range in which data is present, and retrive the values.
var range = secondSheet.getDataRange();
var values = range.getValues();
I have a google form with a dropdown (see below)
I have a column on a google sheet that gets updated everyday.
Is there any way that I can automatically link the names from the google sheet to the google form dropdown Question 1 such that each time the sheet gets updated with an additional name - the google form automatically gets updated with the name in the dropdown. I imagine we would need to use Google AppScript. Any guidance in pointing me in the right direction would be appreciated.
A very generic script but you should be able to modify it as you see fit
function updateForm(){
var ss = SpreadsheetApp.openById('----------'); // ID of spreadsheet with names
var sheet = ss.getSheetByName('Names'); // Name of sheet with range of names
var nameValues = sheet.getRange('A2:A10').getValues(); // Get name values
var form = FormApp.openById('---------'); // ID of form
var formItems = form.getItems();
var question = formItems[2].asListItem(); // Get the second item on the from
var names = []
for(var x = 1; x < nameValues.length; x++){
if(nameValues[x][0] != ""){ // Ignores blank cells
names.push(question.createChoice(nameValues[x][0])) // Create an array of choice objects
}
}
var setQuestion1 = question.setChoices(names); // Update the question
}
To update the form when the sheet is edited you can use an installed onEdit trigger. With the addition of logic you can limit the updting of the form to only occour when a particular range has been edited.
In this example the form will only update when an edit has been made to column A of the sheet 'Names'
function updateForm(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var sheetName = sheet.getSheetName();
var getCol = e.range.getColumn();
if(sheetName == 'Names' && 1){
var nameValues = sheet.getRange('A2:A10').getValues(); // Get name values
var form = FormApp.openById('---------'); // ID of form
var formItems = form.getItems();
var question = formItems[2].asListItem(); // Get the second item on the from
var names = []
for(var x = 1; x < nameValues.length; x++){
if(nameValues[x][0] != ""){ // Ignores blank cells
names.push(question.createChoice(nameValues[x][0])) // Create an array of choice objects
}
}
var setQuestion1 = question.setChoices(names); // Update the question
}
}
Still on a learning curve here. I am trying to get data from a google sheet and send the data Gmail app but getting Missing variable name error. This is what I have tried for the last 2 hours and I will appreciate help in structuring the code to work.
function emailTheLastRow(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("AO2:AO"+sheet.getLastRow()).getValues();
var searchString = "1";
for (var i = 0; i<range.length; i++) {
if(range[i][0] == searchString) {
var lastRow = sheet.getRange(2+i,1,1,41).getValues();
var data = {
'email':lastRow[0][1],
'project':lastRow[0][2],
'client':lastRow[0][3],
'sdate':lastRow[0][4],
'edate':lastRow[0][5],
'loe':lastRow[0][7],
};
GmailApp.sendEmail("test#gmail.com", "Project", "A new project has been created with the following details: " + data());
}
}
}
You're trying to concatenate a string with a JSON, which is an object and not a string. Use stringify function [1] to convert the object to a string. Add this line after you declare data variable:
data = JSON.stringify(data);
[1] https://www.w3schools.com/js/js_json_stringify.asp
thanks in advance for any help.
I'm trying to get data from my Hubspot account into a Google Sheet, using their Analytics API (https://developers.hubspot.com/docs/methods/analytics/get-analytics-data-breakdowns)
I've written the following script in Google App Script:
var url = API_URL + "/analytics/v2/reports/totals/summarize/daily?&start=20181201&end=20181219";
var response = UrlFetchApp.fetch(url, headers);
var json = response.getContentText();
var dataALL = JSON.parse(json);
var dataSet = dataALL;
Logger.log(dataALL);
var rows = [],
data;
for (i = 0; i < dataSet.length; i++) {
data = dataSet[i];
rows.push(data.visits, data.leads);
}
Logger.log(rows)
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
dataRange = sheet.getRange(1, 1, rows.length, 2);
dataRange.setValues([rows])
But when I try Logger.log(rows) it comes out empty. When I try Logger.log(dataSet.length) it returns 0.0
So I gather I'm making a mistake getting the JSON data into the array. I've done tones of research, but could not find a solution that works for my specific case.
The JSON I'm trying to write into the spreadsheet has the following format:
{2018-12-03 = [
{
contactsPerPageview=0.15384615384615385,
rawViews=143,
subscribers=1,
contactToCustomerRate=0.045454545454545456,
privacyConsentDeclines=11,
customersPerPageview=0.006993006993006993,
sessionToContactRate=0.2037037037037037,
pageviewsPerSession=1.3240740740740742,
opportunities=3,
visits=108,
visitors=98,
submissionsPerPageview=0.027972027972027972,
submissions=4,
leads=17,
privacyConsentApproves=9,
customers=1,
contacts=22,
newVisitorSessionRate=0.9074074074074074
}
],
2018-12-14 = [
{
contactsPerPageview=0.06722689075630252,
rawViews=238,
subscribers=4,
privacyConsentDeclines=14,
sessionToContactRate=0.08290155440414508,
pageviewsPerSession=1.233160621761658,
opportunities=6,
visits=193,
visitors=182,
submissionsPerPageview=0.029411764705882353,
submissions=7,
leads=6,
privacyConsentApproves=12,
contacts=16,
newVisitorSessionRate=0.9430051813471503
}]}
Can you guys point me in the right direction?
Thanks again,
Since dataSet is an object, it does not have a .length property, and your for loop will check if i is smaller than Undefined, which results in false. This means the for loop never runs.
I think what you're trying to achieve is closer to the following:
var dataSet = Object.keys(dataALL);
Logger.log(dataALL);
var rows = [], data;
for (i = 0; i < dataSet.length; i++) {
data = dataALL[dataSet[i]];
rows.push(data[0].visits, data[0].leads);
}
Logger.log(rows)
Note that since each key in your object contains an array, I also added [0] to both data.visits and data.leads, resulting in rows.push(data[0].visits, data[0].leads);.
I am pretty new to this forum and also to the google scripts. I have never actually learned JavaScript or any other programming language, however I was forced to start using then since the time I chose the google apps as my main platform for my small business.
My problem is in google ImportRange function limitation to 50 on every spreadsheet. I created a model, where every customer has his own spreadsheet with his personal data, deadlines, etc. located in his own folder in google drive.
I also created a spreadsheet called "Organizer", Organizer has two functions -
1) create automatic correspondention using autoCrat script,
2) show deadlines for every costumer and sort them by priority.
So i need to be able to share / import / copy data from all customer spreadsheets to the "Organizer". Because there are 50+ costumer spreadsheets, I had to give up on ImportRange function and instead of that I am using a simple script to copy files from every spreadsheet directly:
function ImportDataRange() {
// rown number.1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
var range = sheet.getRange(2, 1)
var id = range.getValue()
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
sheet.getRange("B2:AC2").setValues(data)
// row number.2
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
var range = sheet.getRange(3, 1)
var id = range.getValue()
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
sheet.getRange("B3:AC3").setValues(data)
}
This script actually works well, but problem is, when I want to add new costumer spreadsheet to "Organizer" using this method, I have to manually add new copy of whole code for every new row and also change the output range of imported data and location of source file ID in "Organizer".
Does anybody know some kind of workaroud, which will help me to add new rows / costumer data easier / automatically ?
Thank you for your help!
You are going to want to use a loop of some sort. I haven't tested the code below, but based on your example, I think this should work for you.
function ImportOtherSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
// Get the first column
// lastRow() - 1 because we're starting at row 2
var sheetIds = sheet.getRange(2, 1, sheet.getLastRow() - 1);
// For each ID in the id column
for (var i = 0; i < sheetIds.length; i++) {
var id = sheetIds[i]; // Get the id from the Array
// Get the new sheet, range and values
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
// Get the local range, and write the values
sheet.getRange(i + 1, 2, 1, data[0].length).setValues(data)
}
}
As you learn more about GAS and JS, take advantage of MDN and the GAS Documentation
I took the fooby´s code and after long trial-and-error procedure I came with code that is working for me, so if anyone is interested, here it is:
function ShowDataFromOtherSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
var ids = sheet.getRange(2, 1, sheet.getLastRow() - 1).getValues();
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
sheet.getRange(i + 2, 2, 1, data[0].length).setValues(data)
}
}
And thank you fooby - i would not make it without your help!