Google Script stops running because there are no passed arguments - javascript

I have a function which I have been using in google sheets for ages and it worked just fine. After I created a new sheet document and added the function, it stopped working. I have been trying to figure out what has google changed in their API but without any success. This is my function:
/**
* Sums a cell across all sheets
*
* #param {string} cell The cell (i.e. "B2")
* #return number
* #customfunction
*/
function sumAllSheets(cell)
{
var sum = 0;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet().getName();
var sheets = ss.getSheets();
for (var i=1; i < sheets.length; i++) {
var sheet = sheets[i];
var sheetName = sheet.getName();
var sheetRange = sheet.getRange(cell);
sum += parseInt(sheetRange.getValue());
}
return sum;
}
What is basically does is it goes through all of the sheets and sums the the value from a single cell (i.e. cell B2 in all sheets). In previous versions I was able to pass the argument cell as a string by calling the function like so =sumAllSheets("B2"). This worked just fine. However with the new update the cell argument is undefined. Any ideas what's wrong or has been changed? I couldn't find anything in the google documentation.

Are you excluding the first sheet from the sum? If not, "i" should be set to 0 in the first statement of your loop. Also try this variation of your code
function sumAllSheets(cell) {
var sum = 0;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
var v = sheets[i].getRange(cell)
.getValue();
sum += parseInt(v ? v : 0);
}
return sum;
}
Here's an alternative version
function sumCellOnAllSheets(cell) {
return SpreadsheetApp.getActive()
.getSheets()
.map(function (sh) {
return Number(sh.getRange(cell)
.getValue())
})
.reduce(function (a, b) {
return a + b;
})
}

Related

Remove duplicates across multiple sheets

I want to remove duplicates across 2 different sheets.
I have my active sheet, and I want to remove duplicates that already exist in my sheet "Blacklist". I want to run this process for both Column A and Column B (or simply for any values across the entire sheets). When a duplicate is found, I want to leave the row in tact but replace the value with '' (e.g. an empty cell).
I have a working version I mangled together, but only for the active sheet.
N.B. it's the findDuplicate function that I use, the removeDuplicate function I left there not to mess anything up :)
// this is a Google Apps Script project
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{ name: 'Find duplicates...', functionName: 'findDuplicate' },
{ name: 'Remove duplicates...', functionName: 'removeDuplicate' }
];
spreadsheet.addMenu('Duplicates', menuItems);
}
function removeDuplicate() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveRange();
var data = range.getValues();
var rowNum = range.getRow();
var columnNum = range.getColumn();
var columnLength = data[0].length;
var uniqueData = [];
var duplicateData = [];
// iterate through each 'row' of the selected range
// x is
// y is
var x = 0;
var y = data.length;
// when row is
while (x < y) {
var row = data[x];
var duplicate = false;
// iterate through the uniqueData array to see if 'row' already exists
for (var j = 0; j < uniqueData.length; j++) {
if (row.join() == uniqueData[j].join()) {
// if there is a duplicate, delete the 'row' from the sheet and add it to the duplicateData array
duplicate = true;
var duplicateRange = sheet.getRange(
rowNum + x,
columnNum,
1,
columnLength
);
duplicateRange.deleteCells(SpreadsheetApp.Dimension.ROWS);
duplicateData.push(row);
// rows shift up by one when duplicate is deleted
// in effect, it skips a line
// so we need to decrement x to stay in the same line
x--;
y--;
range = sheet.getActiveRange();
data = range.getValues();
// return;
}
}
// if there are no duplicates, add 'row' to the uniqueData array
if (!duplicate) {
uniqueData.push(row);
}
x++;
}
}
function findDuplicate() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveRange();
var data = range.getValues();
var rowNum = range.getRow();
var columnNum = range.getColumn();
var columnLength = data[0].length;
var uniqueData = [];
// iterate through each 'row' of the selected range
for (var i = 0; i < data.length; i++) {
var row = data[i];
var duplicate = false;
// iterate through the uniqueData array to see if 'row' already exists
for (var j = 0; j < uniqueData.length; j++) {
if (row.join() == uniqueData[j].join()) {
// if there is a duplicate, highlight the 'row' from the sheet
duplicate = true;
var duplicateRange = sheet.getRange(
rowNum + i,
columnNum,
1,
columnLength
);
duplicateRange.setValue('');
}
}
// if there are no duplicates, add 'row' to the uniqueData array
if (!duplicate) {
uniqueData.push(row);
}
}
}
Thanks so much for your help! I've been at this for a few hours and figured I should just ask the experts for advice :)
The first lines of both your removeDuplicate and findDuplicate function seems indeed to indicate that you refer to the active spreadsheet / sheet / range
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveRange();
var data = range.getValues();
If you want to be able to use the same function for a given spreadsheet / sheet / range which is not the active one, you will need to use other functions than the getActiveXXX().
For example, to get the sheet named "Blacklist", you should use
sheet = spreadsheet.getSheetByName("Blacklist")
(see also https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetbynamename)
If you want to access a specific range which differs from the active range, you should use the getRange method (see also https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getrangea1notation)
Note that getRange method can be used in different ways, e.g.
getRange("A1:D4"), getRange(1, 1, 3, 3) (the parameters being respectively startRow, startColumn, numRows,numColumns)
Additionally, if you don't want to hardcode the last line of your 2 columns, you will most probably need this function to find the last line in the code :
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getlastrow
(there is also an example there showing how to use getRange() in combination with getLastRow()).
I hope this will help you going further.
Please note that I didn't check the rest of your code and just assumed that your deduplication logic works fine as you mentioned it in your commment.
Good luck !

Matching String to Array

I'm having trouble matching a string in an array. Column B2:Lastrow is defined as array which is "ID". I am trying to paste only unique entries to google sheet which aren't available in Column B2:Lastrow. Issue is..when I run the code it allows duplicates in the google sheet as well.
I was using it through count formula on the sheet but that leads to maximum code runtime error..hence I'm using the range as an array. Solves the error but not able to recognize if the string is unique.
// Code: List Gmail Label to Google Sheet and save attachment to GDrive
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('Summary');
var label = GmailApp.getUserLabelByName("Caterpiller Account");
var threads = label.getThreads();
function getEmails() {
for (var i = 0; i < threads.length; i++) {
var row = sheet.getLastRow() + 1;
var message = threads[i].getMessages()[0];
var ID = message.getId();
var fulldata = sheet.getRange('B2:B' + row).getValues();
if (fulldata.indexOf(ID) == -1) {
var messages=threads[i].getMessages();
var listID=threads[i].getPermalink();
var listdate=threads[i].getLastMessageDate();
var message = threads[i].getMessages()[0];
var attachment = message.getAttachments();
var attachmentBlob = message.getAttachments()[0].copyBlob();
var folder = DriveApp.getFolderById("1ilsecZOexqTWGfAMu5xJDx1pKh3z1US-");
// EXTRACTOR CODE:
for (var m=0; m < messages.length; m++) {
sheet.getRange(row,1).setValue(messages[m].getSubject());
sheet.getRange(row,2).setValue(ID);
sheet.getRange(row,3).setValue(listdate); // Value - Date
for (var z=0; z<attachment.length; z++) {
var file = DriveApp.getFolderById("1ilsecZOexqTWGfAMu5xJDx1pKh3z1US-").createFile(attachmentBlob);
//Pending: Weblinkview (basically get permanent url of file) / Or self developed function that gets file through description (where description is email ID)
}
row++;
}
}
}
}
Expected: Unique entries & a faster Code runtime.
Actual: I'm crap & code time is still the same.
bool IsSame(string str,char arr[100])
{
if(str.lenght!=strlen(arr))return false;
for(int i=0;i<str.lenght;i++)
{
if(str[i]!=arr[i]) return false;
}
return true;
}

Sum cells if they are not bold

I'm confused with my Google Apps script which is purposed to calculate the sum of the cells only if these cells are bold.
Here is the source:
function SumIfNotBold(range, startcol, startrow){
// convert from int to ALPHANUMERIC
// - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
var start_col_id = String.fromCharCode(64 + startcol);
var end_col_id = String.fromCharCode(64 + startcol + range[0].length -1);
var endrow = startrow + range.length - 1
// build the range string, then get the font weights
var range_string = start_col_id + startrow + ":" + end_col_id + endrow
var ss = SpreadsheetApp.getActiveSpreadsheet();
var getWeights = ss.getRange(range_string).getFontWeights();
var x = 0;
var value;
for(var i = 0; i < range.length; i++) {
for(var j = 0; j < range[0].length; j++) {
if(getWeights[i][j].toString() != "bold") {
value = range[i][j];
if (!isNaN(value)){
x += value;
}
}
}
}
return x;
Here is the formula:
=(SumIfNotBold(K2:K100,COLUMN(K2), ROW(K2)))*1
I have three major concerns:
When I set up a trigger to launch this script on any edits I accidentally receive an email from Google Apps stating that
TypeError: Cannot read property "length" from undefined. (line 7, file
"SumIfNotBold")
Thus, how can I fix it? Are there any ways to ignore these automatically delivered notifications?
The formula doesn't calculate the sum of cells if they are on the other list. For example, if I put the formula on B list but the cells are located on A list then this script doesn't work properly in terms of deriving wrong calculations.
When the cell values are updated the formula derivation is not. In this case I'm refreshing the formula itself (i.e., changing "K2:K50" to "K3:K50" and once back) to get an updated derivation.
Please, help me with fixing the issues with this script. Or, if it would be better to use a new one to calculate the sum in non-bold cells then I'll be happy to accept your new solution.
Here is a version of this script that addresses some of the issues you raised. It is invoked simply as =sumifnotbold(A3:C8) or =sumifnotbold(Sheet2!A3:C8) if using another sheet.
As any custom function, it is automatically recalculated if an entry in the range to which it refers is edited.
It is not automatically recalculated if you change the font from bold to normal or back. In this case you can quickly refresh the function by delete-undo on any nonempty cell in the range which it sums. (That is, delete some number, and then undo the deletion.)
Most of the function gets a reference to the passed range by parsing the formula in the active cell. Caveat: this is based on the assumption that the function is used on its own, =sumifnotbold(B2:C4). It will not work within another function like =max(A1, sumifnotbold(B2:C4).
function sumifnotbold(reference) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var formula = SpreadsheetApp.getActiveRange().getFormula();
var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
try {
if (args.length == 1) {
var range = sheet.getRange(args[0]);
}
else {
sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
range = sheet.getRange(args[1]);
}
}
catch(e) {
throw new Error(args.join('!') + ' is not a valid range');
}
// everything above is range extraction from the formula
// actual computation begins now
var weights = range.getFontWeights();
var numbers = range.getValues();
var x = 0;
for (var i = 0; i < numbers.length; i++) {
for (var j = 0; j < numbers[0].length; j++) {
if (weights[i][j] != "bold" && typeof numbers[i][j] == 'number') {
x += numbers[i][j];
}
}
}
return x;
}

Google Sheets Script Copy Values from Array to Column

I'm have an issue where I'm trying to copy values from an array to another column within my active sheet. While I have been following code samples and tutorials on copying values, I get an error with my current setup saying that my Range is not found for
sheet.getRange(resultsArray.length).copyTo(sheet.getRange("F1:F24")).setValues(resultsArray);
I'm not too sure which range it is coming from, but my assumption is the range within the .copyTo method
Here is my full function:
function extractBranded() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
var keywords = /ipad game|game system/;
if (data[i][0].match(keywords)) {
var resultsArray = [];
var brandedKeywords = data[i][0];
resultsArray = brandedKeywords;
Logger.log(resultsArray.length);
Logger.log(shopkeepKeywords);
sheet.getRange(resultsArray.length).copyTo(sheet.getRange("F1:F24")).setValues(resultsArray);
} else {
}
}
}
sheet.getRange wants at least 2 arguments:
(row, col)
or
(row, col, number or rows, number of cols)
sheet.getRange(resultsArray.length) is not a valid range, so you probably need:
sheet.getRange(1,1,resultsArray.length,1)

Iterating over cells in Google Spreadsheet Custom Function

I am trying to build a custom function in Google Spreadsheet, that would basically do this:
- say custom function called func() is placed in cell D2 and invoked as =func(B2)
- provided a particular cell reference (say B2) as a starting point it would iterate over all fields that follow B2 down the column (so B3, B4, B5) while the value of those fields equals to a particular symbol (say pipe |).
- For each iteration where this condition succeeds (i.e B3 == '|') it could add up/aggregate values from the cell it was placed, down the column. So if cells B3, B4,B5 contain | and then B6 doesn't it would return value of D3+D4+D5.
So for example if in this spreadsheet:
In the cells B10 the function should produce value of 8 (1+3+4) and in the cell B15 the function should produce value of 11 (5+6).
I've came up with something like this:
function sumByPipe(startRange) {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(startRange)
var sum = 0;
for (var row_num = 1; row_num < 128; row_num ++) {
var cell = range.getCell(row_num, 1);
var cellValue = cell.getValue();
if (cellValue == '|') {
sum += 1;
}
}
return sum;
}
and got stuck in 2 places really:
Function seems to work in the debugger, but when I invoke it from the spreadsheet it fails on the getRange() function call saying no such range exist. If I replace it with static call of say getRange('A2') that part works but then it fails on the getCell() saying index out of range.
How do I actually get the value of the next cell down the column from where the function itself is placed?
Really quite lost on these two and would appreciate any advice. Thank you!
This works. I tested it:
function sumByPipe(startRange) {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(startRange)
var sum = 0;
var startColumn = range.getColumn();
var startRow = range.getRow();
for (var row_num = startRow; row_num < startRow+128; row_num++) {
var cellWithPipe = sheet.getRange(row_num, startColumn-1).getValue();
var cellValue = sheet.getRange(row_num, startColumn).getValue();
if (cellWithPipe === '|') {
sum += cellValue;
} else {
//If pipe is no longer present, stop and return sum
return sum;
}
}
}

Categories