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
Related
Objective - To copy all non-empty cells from a Spreadsheet-1 to Spreadsheet-2.
I saw some codes online and modified for my use, sharing below.
I need help in getting the script right so that a variable range(i.e. to selects non-empty up to last rows and last columns) can be selected and data copied to Spreadsheet-2.
I am trying to make it workable for 'A1:GZ1000' range.
If numbers of rows / cols with non-zero (non-empty) increases, script needs to update range for passing values to Spreadsheet-2.
''''
function dataImport(ssaID, ssbID) {
// source doc
var ssaID = '1DZX1Jb4qwCHETtAENIsRioJvl4TC0hUWZDn_k1q3oes' ;
var sheet = SpreadsheetApp.openById(ssaID);
var ssbID = '1HptKwYzdWCsz9oey9hOouhWNTQ3GAyu9oswZ1xgP3D0' ;
// source sheet
var ss = sheet.getSheetByName('Data - Price');
// Get full range of data
var SRange = ss.getDataRange();
// get A1 notation identifying the range
var A1Range = SRange.getA1Notation();
// get the data values in range
var SData = SRange.getValues();
// Logger.log(SData)
// target spreadsheet
var tss = SpreadsheetApp.openById(ssbID);
// target sheet
var ts = tss.getSheetByName('Data - Price');
// Clear the Google Sheet before copy
ts.clear({ contentsOnly: true });
Logger.log(SRange.length);
// set the target range to the values of the source data
var tsRange = ts.getRange(1,1,SRange.length,SRange[0].length);
tsRange.setValues(Sdata);
}
''''
Pl. do ask for details if you require.
R U
Try it this way:
function dataImport(ssaID, ssbID) {
var ssaID = '1DZX1Jb4qwCHETtAENIsRioJvl4TC0hUWZDn_k1q3oes';
var ss = SpreadsheetApp.openById(ssaID);
var ssbID = '1HptKwYzdWCsz9oey9hOouhWNTQ3GAyu9oswZ1xgP3D0';
var sh = ss.getSheetByName('Data - Price');
var rg = sh.getDataRange();
var vs = rg.getValues();
var tss = SpreadsheetApp.openById(ssbID);
var tsh = tss.getSheetByName('Data - Price');
tsh.clearContents();
tsh.getRange(1, 1, vs.length, vs[0].length).setValues(vs);
}
I am new with javascript and I am trying to do a script that copy the value of the last raw of a sheet to the last raw of another sheet, if I donĀ“t set the number of columns to the range it only copy one value, however if I set the amount of columns it only returns that copy to is not a function, please if you can help me.
This is the code I am using:
function ORderReservation() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var hOrigen = spreadsheet.getSheetByName('Form responses 1');
var hDestino = spreadsheet.getSheetByName('TODAS AGENCIAS');
var filActiva = hOrigen.getLastRow();
var activeCell =hOrigen.getRange(filActiva,1)
var valor = activeCell.getValue();
if( valor>= 0)
var rngOrgn = hOrigen.getRange(filActiva,1,1,8).activate;
var detsin = hDestino.getLastRow()+1;
rngOrgn.copyTo(hDestino.getRange(hDestino.getLastRow()+1,1,1,8),SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
}
I have a spreadsheet connected to a google form, however I have another tab "sheet3" which uses array formula from "Form Responses 1".
The script I am using which sends all questions and answers to other emails does not take the info from "sheet3", only from "Form responses 1".
I have tried so many different things and nothing. Here's my script:
function sendFormAnswers(data) {
Logger.log("sendEmail");
var values = SpreadsheetApp.getActiveSheet();
var row = values.getLastRow();
var s = SpreadsheetApp.getActive().getSheetByName("sheet3").activate();
var headers = s.getRange(1,2,1,s.getLastColumn()-1).getValues()[0];
var values = s.getRange(s.getLastRow(),1,s.getLastRow(),s.getLastColumn()-1).getValues()[0];
var row = values[0];
var timestap = values[0];
var ABS = values[1];
var OPS = values[2];
many thanks
I am new to this and I am having some trouble trying to figure this out. I have a spreadsheet that collects data from a google form. I am trying to find a way to move that data based on a column answer to a different google sheet. (Not a sheet in the same document but a different document all together). It seems like there is some information about moving to a different tab in the same document, but not a different document.
I will first say that I tried just an IMPORTRANGE function, but that only mirrors the data, and does not let you update or change cells.
Here is what I have been able to piece together so far, but I may be way off.
I have a trigger that would run every hour.
function myFunction() {
var ss = SpreadsheetApp.openById('1U0I9SkbGkHgm-vRkwf2Ppc_yxlqrVlg2t8yKRy3sYuI');
var sheetOrg = ss.getSheetByName("Form Responses 1");
var value1ToWatch = "ANDERSON";
var value2ToWatch = "BARNES";
var sheetNameToMoveTheRowTo = "Sheet1"; //sheet has same name for each target openByID(" *url key* ")
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ts1 =SpreadsheetApp.openById("1PxV1PQrMdu_2aSru4dpan8cUgHYdlYPUp5anyzjMAms");
sheet1in = ts1.getSheetByName("Sheet1");
var ts2 = SpreadsheetApp.openById("1BYyQZNiXc2QqsyqWs7uazjl5B6mfFYM1xj3u8gWyYOQ");
sheet1in = ts2.getSheetByName("Sheet1");
arr = [],
values = sheetOrg.getDataRange().getValues(),
i = values.length;
while (--i) {
if (value1ToWatch.indexOf(values[i][1]) > -1) {
arr.unshift(values[i])
sheetOrg.deleteRow(i + 1)
sheet1in.getRange(sheet1in.getLastRow()+1, 1, arr.length,
arr[0].length).setValues(arr);
};
if (value2ToWatch.indexOf(values[i][1]) > -1) {
arr.unshift(values[i])
sheetOrg.deleteRow(i + 1)
sheet2in.getRange(sheet2in.getLastRow()+1, 1, arr.length,
arr[0].length).setValues(arr);
};
}
}
The sheet google forms dumps the information into is "Form Responses 1".
Column B is the cells I want to get the values from. (There are a total of 9 different values that it can be like "ANDERSON", "BARNES", "SMITH", etc).
For sheetNameToMoveTheRowTo is "Sheet1" - that may be confusing and I may need to change that, but for example
ts1 =SpreadsheetApp.openById("1PxV1PQrMdu_2aSru4dpan8cUgHYdlYPUp5anyzjMAms") the sheet name that I want the information moved to is "Sheet1".
ts2 = SpreadsheetApp.openById("1BYyQZNiXc2QqsyqWs7uazjl5B6mfFYM1xj3u8gWyYOQ") the sheet name is also "Sheet1" but in a different document.
I think if I were able to get the "ANDERSON" one to work, then I can just add additional variables for each possible response, and just copy and paste additional "IF" statements, just changing the valueToWatch and targetSheet values. <= if that is not correct please let me know
I have tried to both debug, and run the script above but nothing happens. There are no errors reported on the debug, but it is not moving any information over.
Any idea what I am doing wrong?
// UPDATE I got this to work. I have updated the code listed with what worked for me.
I think that copyTo() method will not work like you mentioned, it operates on same SpreadSheet. I'm sending you example with looping on source sheet data and then setting the target sheet values with it.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var allrange = ss.getActiveRange();
var range = sheet.getRange("A1:A10");
var values = range.getValues();
var allvals = [];
for(var i = 0; i < values.length; i++) {
allvals.push( values[i] ) ;
}
var dataLength = allvals.length;
// alert data
var ui = SpreadsheetApp.getUi();
// ui.alert( JSON.stringify(allvals) )
// copy to new Google SpreadSheet
var newSheet = SpreadsheetApp.openById('1F79XkNPWm2cCWlB2JP3K4tAYRESKUgtHK4Pn2vbJEiI').getSheets()[0];
var tmp = "A1:A" + dataLength ;
var newRange = newSheet.getRange( tmp );
newRange.setValues( allvals );
}
Here's a simple example of moving data from one spreadsheet to another.
function movingDataToSS(){
var ss=SpreadsheetApp.getActive();
var dss=SpreadsheetApp.openById('ssId');
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var dsh=dss.getSheetByName('Sheet1');
var drg=dsh.getRange(1,1,rg.getHeight(),rg.getWidth()).setValues(vA);
}
If you interested in placing some conditions on your output by only getting output from odd rows and even columns.
function movingDataOddRowsAndEvenCols(){
var ss=SpreadsheetApp.getActive();
var dss=SpreadsheetApp.openById('ssId');
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var h=rg.getHeight();
var w=rg.getWidth();
var dsh=dss.getSheetByName('Sheet1');
for(var i=0;i<h;i++){
var out=[];
if(i%2==0){
for(var j=0;j<w;j++){
if(j%2==1){
out.push(vA[i][j]);
}
}
dsh.appendRow(out);
}
}
}
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');