How to reference a value in a different sheet? - google-apps-script

This is prob simple but I'm new to this. I'm trying to map out my variables at the beginning of a Google Form>Spreadsheet>Template Doc workflow. The form fills out the following 4 columns (timestamp through campaign_start_date) but the other 2 columns (insertion_order_number and month) are values that are coming from a different sheet in the SAME google spreadsheet/workbook. How do I reference these values?
//e.values is an array of form values
var timestamp = e.values[0];
var client = e.values[1];
var advertiser = e.values[2];
var total_spend_amount = e.values[3];
var campaign_start_date = e.values[4];
var insertion_order_number =
var month =

As mentioned in the above comment.
You want to open a spreadsheet by it's ID.
Once you have that spreadsheet you want to the range where "Campiagn Start Date" and Insertion Order Month" are in.
Once you have that range, you want to get the value(s) inside that range.
Then you can assign the value of those two variables to be the value that you got above.
The below code is an example of what you could do.
I would highly advise using getValues() over getValue.
But for the purpose of this sample code, will keep it nice and simple:
function onSubmit(e) {
//Get Spreadsheet by ID and get sheet by name
var ss = SpreadsheetApp.openById("YOUR ID HERE");
var sheet = ss.getSheetByName("YOUR SHEET NAME HERE");
var campiagnStartDate = sheet.getRange(2, 2, 1, 1).getValue(); //Gets the value in B2
var insertionOrderMonth = sheet.getRange(2, 3, 1, 1).getValue(); //Gets the value in B3
var timestamp = e.values[0];
var client = e.values[1];
var advertiser = e.values[2];
var total_spend_amount = e.values[3];
var campaign_start_date = e.values[4];
var insertion_order_number = campiagnStartDate
var month = insertionOrderMonth
}

Related

Function to clear a cell based on clicking on a URL in a Google Spreadsheet to reopen a form?

Is it possible to create a function that will clear a cell when a URL on the active row is clicked? I need to clear the cell on the active row in column AG, or [32], whenever the response link on that cell is activated to be opened to go back to the form.
I have the code that creates the date value in the column I need cleared. The code is to disburse emails automatically (on a trigger) when an email is submitted. However, when a response needs to be added to the form, the 'Response Link' needs to be activated so the user can be taken back to the form to fill in response data. I want the emails to go out again when the form is updated. But because I added a date there to stop emails from going out over and over, updated emails cannot send. Once the form is resubmitted, it will put a date back into the cell.
function disburseEmails(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Form Responses 1');
var allRange = sheet.getDataRange();
var allData = allRange.getValues();
allData.shift();
allData.forEach(function(row,i) {
if(row[32] === '') {
// get data
var dateSubmitted = row[0];
var dateEdited = row[1];
var studentID = row[2];
var studentName = row[3];
var responseLink= row[4];
var submitRespond = row[5];
var senderName = row[6];
var senderEmail = row[7];
var senderPhone = row[8];
var senderExt = row[9];
var senderRole = row[10];
var senderReason = row[11];
var senderAdditional = row[12];
var householdName = row[13];
var householdAddress = row[14];
var householdPhone = row[15]
var studentGrade = row[16];
var studentSchool = row[17];
var anySiblings = row[18];
var sibling1Name = row[19];
var sibling1Grade = row[20];
var sibling1School = row[21];
var sibling2Name = row[22];
var sibling2Grade = row[23];
var sibling2School = row[24];
var additionalSiblings= row[25];
var numberHomeVisit = row[26];
var responseContactName = row[27];
var responseContactRelationship = row[28];
var responseOutcome= row[29];
var responseAdditional = row[30];
var email = row[31];
var confirmSenderEmail = row[32];
// send an email to the sender for each row
sendEmail(dateSubmitted, email, dateEdited, studentID, studentName, responseLink, submitRespond, senderName, senderEmail, senderPhone, senderExt, senderRole, senderReason, senderAdditional, householdName, householdAddress, householdPhone, studentGrade, studentSchool, anySiblings, sibling1Name, sibling1Grade, sibling1School, sibling2Name, sibling2Grade, sibling2School, additionalSiblings, numberHomeVisit, responseContactName, responseContactRelationship, responseOutcome, responseAdditional);
// add date to confirm the sender email went out
var d = new Date();
sheet.getRange(i + 2, 33).setValue(d);
}
});
}
Let's asssume you have the links the needed in the F column:
function onSelectionChange(e) {
var range = e.range;
var sheet = e.range.getSheet();
if(range.getColumn() == 6) {
sheet.getRange("RANGE_OF_THE_CLEARED_CELL").clear();
}
}
The above snippet uses an onSelectionChange(e) trigger which will trigger whenever a cell is selected. In order to check that a cell from the F row is selected, a condition is set and based on that, the cell wanted is cleared.
The code makes use the e event object which contains information about which cell has been selected.
Note
This works for all the cells in the F column, so if you want to make it specific to a particular cell, you can just add another condition and/or a loop to reflect the data you want accordingly.
Reference
Apps Script Triggers;
Apps Script Event Objects ;
Apps Script Class Sheet - getRange

How to find a column value within an active row

How do I find the data in a column within an active row that is already defined in Google Apps Script?
I have an on edit function that sends an email when a column f is edited to a specific value. I need to find out the value in column b in order to include the value in the body of the message.
I have tried to use a range, but I am not understanding how i can define the second column for the active range that is already defined in the row variable. Here is what my code looks like. var called Values is the row of code I need help with. The row var is looking at the correct row. Any help is greatly appreciated.
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var sheetName = sheet.getName();
var cell = sheet.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = sheet.getActiveCell().getValue().toString();
var values = row.getcell()[0,2].getvalue().toString();
var recipients = "kel...#trafficbuilders.us";
var message = '';
if(cellvalue === '✔'){
message = 'All Items have been received for .';
var subject = 'All Items have been received for ' ;
var body = message + ' Visit ' + ss.getUrl() + ' to view the changes';
MailApp.sendEmail(recipients, subject, body);
}
}
To fetch a certain data/value from a certain cell, here's what you can do:
First identify the cell where data is located using getRange(). There are several ways to use getRange.
Sample from the docs:
// Get a range A1:D4 on sheet titled "Invoices"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange("Sheet!A1:D4");
// Get cell A1 on the first sheet
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("A1");
To actually fetch the content/data, use getValues() or getValue()
sample snippets:
// The code below gets the values for the range C2:G8
// in the active spreadsheet. Note that this is a JavaScript array.
var values = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getValues();
Logger.log(values[0][0]);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Passing only two arguments returns a "range" with a single cell.
var range = sheet.getRange(1, 1);
var values = range.getValues();
Logger.log(values[0][0]);

GAS - Select (Get) Spreadsheet per GForm input

My 1st question in Stack Overflow.
I have a Google Spreadsheet with 4 individual sheets.
Sheet1 is responses from GForm. Sheet2,3,4 have same data but in 3 languages English, Tamil, Hindi and named English, Tamil, Hindi.
At present the Script takes cell value date from Sheet1, matches the data in the language Tamil sheet, mail merges with the correct language Tamil GDoc and emails it.
Now, I cannot figure out how to make the Script pick a different language Gsheet, one of the 3, depending upon the evalues4 from Form input, which is a Radio Button.
Can someone help me to figure it out?
Select appropriate language
Gsheet using ss.getSheetByName and
GDoc using DriveApp.getFileById
based on Form response evalues4.
Here is the code and which works fine, if I input just one language by name/sheetID/DocID.
//Get information from the form and set as variables
function onFormSubmit(e)
{
var Time = e.values[0];
var email = e.values[1];
var fog = e.values[2];
var mog = e.values[3];
var lang = e.values[4];
var do_date = e.values[5];
//Match chosen date from data sheet & get Row Number
function findInColumn() {
var data = do_date;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("Tamil");
var range = sheet1.getRange(1,1,sheet1.getLastRow(),1);
var values= range.getValues();
var row = 0;
while ( values[row] && values[row][0] !== data ) {
row++;
}
if (values[row][0] === data)
return row+1;
else
return -1;
}
//Use above Row number to load in Range, get values, assign to variable cells
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet3 = ss.getSheetByName("Tamil");
// Get range of cells in All columns and All rows with entries
var dataRange = sheet3.getRange(findInColumn(), 1, 1, sheet3.getLastColumn());
// Get entries for each row in the Range.
var data = dataRange.getValues();
// Set each value to a unique variable
for (i in data) {
var cell = data[i];
// Get document template, copy it as a new doc with Name and email, and save the id
var copyId = DriveApp.getFileById("1Nxxxxxxxxxxxxxx2k")
Sorry, completely forgot that I had asked the question here. I solved it the same weekend, by using the If - else [Note: Instead of var ss I used var ssn, and instead of var sheet3 I used var tocopyID in the rewrite]
//Use above Row number to load in Range, get values, assign to variable cells
var ss = SpreadsheetApp.getActiveSpreadsheet();
if (lang === "Tamil"){
var ssn = ss.getSheetByName("Tamil");
var tocopyId = DriveApp.getFileById("1NxxxxTamil");
}
else if (lang === "Hindi"){
var ssn = ss.getSheetByName("Hindi");
var tocopyId = DriveApp.getFileById("Hindi");
}
else if (lang === "English"){
var ssn = ss.getSheetByName("English");
var tocopyId = DriveApp.getFileById("1NxxxxEnglish");
}
You could use you lang variable to get the correct sheet, since they've got the same name. Like :
var sheet1 = ss.getSheetByName(lang); // where lang = "Tamil" for example
For using the correct template, you can store the id of your template with the Properties like:
var templateId = PropertiesService.getScriptProperties().getProperty(lang); // where lang = "Tamil" for example
var copyId = DriveApp.getFileById(templateId);
Where you have properties set with the language name you want. You can set them with code :
PropertiesService.getScriptProperties().setProperty('Tamil', '1Nxxxxxxxxxxxxxx2k');

Script issue with an array reference

Please excuse the length of the post I was getting help but the person has not been online for the last week so thought I would try here to get the last few kinks out. Thank you for any extra help.
Here is my original script.
function ImportDataRange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("AM trip"); //To Sheet Name
var ssraw = SpreadsheetApp.openById("1n4**4HzvVS****RQhPHndUbn0N0nkpOE5NpO2U"); // From Spreadsheet ID
var sheetraw = ssraw.getSheetByName("AM trip"); // From Sheet name
var range = sheetraw.getRange("B9:U38");
var data = range.getValues();
sheet.getRange("C1").setValues(data)
}
My adjusted script:-
function ImportDataRange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('AM trip'); //To Sheet Name
var ssraw = SpreadsheetApp.openById('18h-UAy10EvANHZXLebspZsUbE2fisyEBAFnUYV9JBHs'); // From Spreadsheet ID
var sheetraw = ssraw.getSheetByName('AM trip'); // From Sheet name
var range = sheetraw.getRange('B7:U38');
var data = range.getValues();
var lastRow = sheet.getRange(sheet.getLastRow()+1,3).setValue(data);
}}
This takes B7 from the original spreadsheet and places it in the next blank row down and in Column C but not B7:U38, if i change setValue(data) to setValues(Data) I get the range height error.
Then below, I got from you and below the script is the error it produces:-
function ImportDataRange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('AM trip'); //To Sheet Name
var ssraw = SpreadsheetApp.openById('18hAy10EvANHZXLebspZsUbE2fisyEBAFnUYV9JBHs'); // From Spreadsheet ID
var sheetraw = ssraw.getSheetByName('AM trip'); // From Sheet name
var range = sheetraw.getRange('B7:U38');
var data = range.getValues();
var lastRow = sheet.getLastRow()+1;
setValues(sheet, lastRow, 3, data);
The reason for the error is range height should match the height of the data being input.
You will have to modify the code like so
function ImportDataRange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('AM trip'); //To Sheet Name
var ssraw = SpreadsheetApp.openById('18hAy10EvANHZXLebspZsUbE2fisyEBAFnUYV9JBHs'); // From Spreadsheet ID
var sheetraw = ssraw.getSheetByName('AM trip'); // From Sheet name
var range = sheetraw.getRange('B7:U38');
var data = range.getValues();
var lastRow = sheet.getLastRow()+1;
sheet.getRange(lastRow,3,data.length,data[0].length).setValues(data)
}
Basically, get the length of the data array use array.length gives you number of rows. You find more details on it here
Details on setValues can be found here, similarly details on getRange can be found here
Hope that helps

Sum up numeric inputs in a Google Form

SOF friends,
I have a form which has a bunch of numeric fields among some date and string fields.
How to add up the numeric values and include the total as a column in the spreadsheet where it saves the responses? Where do I write the script for this? At the form level or at the spreadsheet level?
Here's what I have at this time, as a trigger on form submit which doesn't work:
function myFunction() {
Logger.log("Spreadsheet: %s", SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName());
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//sheet.setActiveSelection("M1:M").clear();
var range = sheet.getDataRange();
var values = range.getValues();
var lastrow = range.getLastRow();
var lastcolumn = range.getLastColumn();
Logger.log(lastrow);
Logger.log(lastcolumn);
Logger.log(values[lastrow][10]);
var coll = values[lastrow][6];
var drv = values[lastrow][7];
var clnr = ((values[lastrow][8] != "")? values[lastrow][8]:0);
var dsl = values[lastrow][10];
var gen = values[lastrow][11];
var tot = coll + drv + clnr + dsl + gen;
var singlecell = sheet.getRange(lastrow, 13);
singlecell.setValue(tot);
Logger.log(tot);
}
Code
Example of code to be added to a project bounded to a spreadsheet.
function sumFormResponseItems(e) {
var firstSummand = parseInt(e.namedValues['First summand'][0],10);
var secondSummand = parseInt(e.namedValues['Second summand'][0],10);
var range = e.range;
var row = range.getRow();
var lastColumn = range.getLastColumn();
range.getSheet().getRange(row,lastColumn+1).setValue(firstSummand + secondSummand )
}
After you add the code, add an on form submit trigger to make it work.
Explanation
The above code sums only the values of the submitted response instead of doing the same for the whole sheet data range that potentially could return you an exceeded execution time limit error because your codes uese an open ended reference.
Regarding if adding the script to a spreadsheet or to a form, without more details any answer will be opinion based.
References
https://developers.google.com/apps-script/guides/triggers/events