error when retrieve values from google script spreadsheet - google-sheets

I have this script in google script spreadsheet:
function doGet() {
var response = [];
var ss = SpreadsheetApp.getActive();
var thisSheet = ss.getSheetByName('product');
var lastRow = thisSheet.getLastRow();
var allValues = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var objectResponse = {};
for(var i = 2; i < lastRow ; ++i){
objectResponse.title = allValues[i][1];
objectResponse.url = allValues[i][8];
response.push(objectResponse);
};
return ContentService.createTextOutput(JSON.stringify(response)).setMimeType(ContentService.MimeType.JSON);
}
I make this loop to create an array of objects like this
[
{ title: 'first_title_on2column' , URL: 'first_url_on9column'},
{ title: 'second_title_on2column' , URL: 'second_url_on9column'},
...
//until ends <lastRow>
]
but the results is the same on each object. Same 'title' and 'URL'.
How to retrieve each 'title' and 'URL' values?

your code does not add new object elements to the response array, but only new references to the same object - so all your values are the same
var objectResponse = {};
for(var i = 2; i < lastRow ; ++i){
objectResponse.title = allValues[i][1];
objectResponse.url = allValues[i][8];
response.push(objectResponse);
};
try replacing your code block with a new one and see what happens
for(var i = 2; i < lastRow ; ++i){
response.push({title: allValues[i][1], url:allValues[i][8]});
};
or even like this
allValues.forEach(dataRow => response.push({title: dataRow[1], dataRow[8]}))

Related

How do i get the URL of a editable form response in spreadsheets

Im trying to get the url of a editable google form response to show up in google sheets,but it does not seem to be working.
I have seen Awesome Table and Ruben's example. Based of these 2 links and some others, they seem to be working for single form response sheets,but not multiple.
I tried this code 1st:
var formURL = 'https://docs.google.com/forms/d/__Your ID__/viewform';
var sheetName = '__Response sheet__';
var columnIndex = __column where it appears__;
function getEditResponseUrls() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openByUrl(formURL);
for(var i = 2; i < data.length; i++) {
if (data[i][0] != '' && data[i][columnIndex-1] == '') {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if (formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex).setValue(editResponseUrl);
}
}
}
2nd is:
// Form URL
var formID = '__Your ID__';
// Sheet name used as destination of the form responses
var sheetName = '__Response sheet__'';
/*
* Name of the column to be used to hold the response edit URLs
* It should match exactly the header of the related column,
* otherwise it will do nothing.
*/
var columnName = '__name of column where it appears__' ;
// Responses starting row
var startRow = 2;
function getEditResponseUrls(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var columnIndex = headers[0].indexOf(columnName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openById(formId);
for(var i = startRow-1; i < data.length; i++) {
if(data[i][0] && !data[i][columnIndex]) {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if(formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex+1).setValue(editResponseUrl);
}
}
}
Nothing is showing up, and when i check the logs for triggers, it is all working fine, no failures.I have tried putting the global variables within the function, but no changes.
The following points are taken from the latest version from #Rubén latest version on github. This code is a thing of beauty and a joy to behold. Combined with Rubén's detailed instructions, this answer can be setup and running in less than 5 minutes.
change
var formID = '__Your ID__';
to
var formURL = 'https://docs.google.com/forms/d/ -insert id - /edit';
you get the URL from the Forms Editor page.
change
var columnName = 'Form URL';
to
var sheetName = 'URL'; // Column U
replace getEditResponseUrls entirely
function getEditResponseUrls(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var columnIndex = headers[0].indexOf(columnName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openByUrl(formURL);
for(var i = startRow-1; i < data.length; i++) {
if(data[i][0] != '' && data[i][columnIndex] == '') {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if(formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex+1).setValue(editResponseUrl);
}
}
}
Remember to set the installable trigger.
In the Google Sheet that you have linked from the question above, you have declared two functions with the same name and this could be a reason why the first one may never be executing. I tested this code and it seemed to work.
You may want to replace everything in the file with just this code.
var id = '1SdSPhOwi1dWQzRsNpA9zFL-ODorgohST3TMRJLqz16I';
var sheetName = 'Order Information';
var columnIndex = 21;
function getEditResponseUrls() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openById(id);
for(var i = 2; i < data.length; i++) {
if (data[i][0] != '' && data[i][columnIndex-1] == '') {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if (formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex).setValue(editResponseUrl);
}
}
}

Sum if Bold with criteria in google sheet

I have used google script below
function sumWhereIsFontWeight(rangeSpecification,) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange(rangeSpecification);
var x = 0;
for (var i = 1; i <= range.getNumRows(); i++) {
for (var j = 1; j <= range.getNumColumns(); j++) {
var cell = range.getCell(i, j);
if(cell.getFontWeight() == 'bold')
x += parseFloat(cell.getValue());
}
}
return x;
}
Then used formula =SUMIF(A:A,"A"&sumWhereIsFontWeight(B1:B6),B1:B6)
But cannot get the desired result "10" of sum only bold numbers with criteria as "A". Check the image attached
Usage
=ArrayFormula(SUM(IF(isbold("A1:B10"),A1:B10,0)))
The function
function isBold(rangeSpecification) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange(rangeSpecification);
var result = [];
var numRows = range.getNumRows();
var numCols = range.getNumColumns();
var row = [];
for (var i = 1; i <= numRows; i++) {
row = [];
for (var j = 1; j <= numCols; j++) {
var bold = (range.getCell(i,j).getFontWeight() === 'bold');
row.push(bold);
}
result.push(row);
}
return result;
}
Caution
A custom function won't update automatically when you add new bold cells. You need to re-enter the formula.

Getting error: "Missing ) after argument list. (line 11, file "Code")

I'm new to coding. I am attempting to import e-mail addresses from a Google Sheet to my gmail account. Any help on why this code is not working would be greatly appreciated! Here is the code I have entered:
function myFunction() {
var alreadyAdded = "Already added";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 396; // Number of rows to process
// Fetch the range of cells A2:F397
var dataRange = sheet.getRange(startRow, 1, numRows, 400
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for
var
for (var i = 0; i < data.length; ++i)
};
var row = data[i];
var lastName = row[0]
var firstName = row[1]
var emailAddress = row[2]
var address = row[3]
var notes = row[4]
if (addedAlready != alreadyAdded) {
// Create contact in Google Contacts
var contact = ContactsApp.createContact(firstName, lastName, emailAddress);
// Add values to new contact
contact.addAddress(address, "");
contact.setNotes(notes);
sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
};
};
}
try it var dataRange = sheet.getRange(startRow, 1, numRows, 400);

Google Script send email from a sheet in a specific date

follow script is used to get a date from a google sheet and if this date is equal to today or tomorrow generate an automatic email to my address in order to remind me.
function getVal() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
sheet = ss.getActiveSheet();
sheet.setActiveRange(sheet.getRange("A1"));
var range = sheet.getDataRange(),
formulas = range.getValues();
var toDay = new Date();
for (var r=0; r<formulas.length; r++) {
for (var c=0; c<formulas[r].length; c++) {
//var value = sheet.getRange(r,c).getValue();
var value = range.getCell(r, c).getValue();
Logger.log(value);
if (value == "AAAA")
{
var index = r+2;
value = sheet.getRange(index,c).getValue();
while (value != "" || index >= formulas.length)
{
if (DateDiff.inDays(value,toDay)==1 || DateDiff.inDays(value,toDay)==0)
{
MailApp.sendEmail(myAdress,subject, text);
}
index = index + 3;
value = sheet.getRange(index,c).getValue();
}
}
}
}
}
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
when i run the script it fail in the line :
var value = range.getCell(r, c).getValue();
have you any suggestion in order to fix this bug?
thanks
Mario
try to change the line with:
var value = formulas[r][c]
it should also do less request to google spreadsheet and run faster.

How to count cell values based on the background color in Spreadsheet

I am trying to count the values in a cell based on the background color. Someone I got some help while online search I am not getting the complete solution. Does anyone help me out with this prob. I have sample code script which I got from the online search.
Also the script which am pasting here is grouping the values( For Example if i have a value A in three cells it should return the value as 3 instead it is returning AAA. Can someone help me out with the script to count the values and return it based on the background color
Thanks in Advance,
Here is the script:
function sumBackgroundColors(rangeString, color) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var sumRange = s.getRange(rangeString);
var sum = 0;
var sumRangeBackground = sumRange.getBackgroundColors();
var sumRangeValues = sumRange.getValues();
for(var row = 0; row < sumRangeBackground.length; row++ ) {
for(var col = 0; col < sumRangeBackground[0].length; col++ ) {
if( sumRangeValues[row][col]=="LG M"&& sumRangeBackground[row][col] == color ) {
sum = sum + parseFloat(sumRangeValues[row][col]);
}
}
}
return sum;
}
I recommend you to not use a custom function to do this because of its caching feature (explanation here).
function countBackgroundColors() {
var rangeString = "A1:A100";
var color = "green";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var range = s.getRange(rangeString);
var count = 0;
var rangeColors = range.getBackgroundColors();
for( var i in rangeColors )
for( var j in rangeColors[i] )
if( rangeColors[i][j] == color )
++count;
return count;
}

Resources