"for" loop for Google Spreadsheet values not looping - for-loop

I'm currently writing a statistic spreadsheet script for my guild, which reads out the class of one person and counts it on the statistic sheet.
For some reason the for loops aren't working. When I execute the script, it does nothing. Everything before the for loop seems to work. I have used the debugger, and set a debug point from the point of the for loop and the window is opening and closing after like 1 second.
This is my code as of now:
function addToStatistik() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = spreadsheet.getSheetByName("Raid Montag");
var source_range_names = source_sheet.getRange("C4:C13");
var source_range_setup_boss1 = source_sheet.getRange("M4:M13");
var target_sheet = spreadsheet.getSheetByName("Statistik");
var target_range_names = target_sheet.getRange("A4:A31");
var target_range_boss1 = target_sheet.getRange("K4:S31");
target_sheet.getRange(2,1).setValue("Debug1"); //testing stuff
for (var i=0; i < source_range_names.length; i++) {
for (var j=0; j < target_range_names.length; j++) {
if (source_range_names[i][0] == target_range_names[j][0]) {
if (source_range_setup_boss1[i][0].indexOf("War") > -1) {
target_sheet.getRange(9,5).setValue("TEST");
}
}
}
}
}
Someone can find any errors in there? I can't find anything and google also isnt helping me.

You are getting the range, but not the values. This line:
var source_range_names = source_sheet.getRange("C4:C13");
gets a range, but not any values.
Should be:
var source_range_names = source_sheet.getRange("C4:C13").getValues();
The outer loop never loops. There is no length of a range.
for (var i=0; i < source_range_names.length; i++) {
You don't need to change the above line, but currently the variable source_range_names is a range, and not a 2D array of values.

Before you iterate you need to get the values of the range, to achieve this you need to use the method getValues() or getDisplayValues():
function leFunction() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = spreadsheet.getSheetByName("Raid Montag");
var source_range_names = source_sheet.getRange("A1:C13");
var values_range_names = source_range_names.getDisplayValues();
Logger.log(values_range_names);
for (var i=0; i < values_range_names.length; i++) {
// Do Something
}
}

Related

For loop not looping through spreadsheet

I made a small search box to retrieve values from a datasheet. For some reason it only loops once. Also this is the first time I'm trying something in google sheets, so if I want to search a string in column B, then the SEARCH_COL_IDX should be 1 right?
I put in a few loggers to check the process. I do see Logger.log(str), Logger.log("Check") and Logger.log("Check2). The latter two only once, where it should be multiple times imo. The Logger.log(row[#]) I don't get to see at all, which means it doesn't find anything.
I also tried doing if(row[SEARCH_COL_IDX] = str) { to see where it is looking. Than the Logger.log(row[#]) do come back, but from different rows AND columns. I am doing something wrong, but I can't find it.. any suggestions?
var SPREADSHEET_NAME = "Database";
var SEARCH_COL_IDX = 1;
var RETURN_COL_IDX= 1;
function searchStr(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Userform");
var str = formSS.getRange("d17").getValue();
Logger.log(str);
var values = ss.getSheetByName("Database").getDataRange().getValues();
for (var i = 0; i < values.length; i++) {
Logger.log("check");
var row = values[i];
Logger.log("check2");
if(row[SEARCH_COL_IDX] == str) {
formSS.getRange("d3").setValue(row[0]);
Logger.log(row[0]);
formSS.getRange("d5").setValue(row[1]);
Logger.log(row[1]);
formSS.getRange("d7").setValue(row[2]);
Logger.log(row[2]);
formSS.getRange("d9").setValue(row[3]);
Logger.log(row[3]);
formSS.getRange("d11").setValue(row[4]);
Logger.log(row[4]);
formSS.getRange("d13").setValue(row[5]);
Logger.log(row[5]);
}
Logger.log("nothing found");
return row[RETURN_COL_IDX];
}
Your function has a return command in the last line of your loop block.

GSheet Script: How to Optimize my Row and Sheet Iterator

Long story short, I have this bit of Google Script that clears content automatically in a GSheet. It is set on a trigger and it works...the code does what it's supposed to do. The issue is that it runs slow. It takes 2 to 3 minutes for the iterator to run. To help you scope the size of the task: there is 150 rows on each of the 8 sheets.
The objective of the code is to clear a number of rows on each sheet based on the value of the cell in the first column of a row.
So I would like to know if anyone has any insight or suggestion to improve the running time. I understand my method of using a for loop checks rows one by one, and that's a time-consuming task. I couldn't think of an alternate method with arrays or something?
Thanks all!
Here's the code:
function Reset_Button() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i = 1; i < sheets.length ; i++ ) {
var sheet = sheets[i];
sheet.getRange("C2").setValue(new Date());
var rangeData = sheet.getDataRange();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(1,1, lastRow, 1);
for ( j = 1 ; j < lastRow ; j++){
var value = sheet.getRange(j,1).getValue()
if(value === 0){
sheet.getRange(j,2,1,5).clearContent()
}}}}
Typically you want to do as few writes to the spreadsheet as possible. Currently your code goes through each line and edits it if necessary. Instead get the entire data range you will be working with into one variable (let's say dRange and use .getValues() to get a 2d array of all the values into a second variable (let's say dValues). Then simply iterate over dValues, setting a blank "" in each you want to clear. Once you are done going over all values, just do a dRange.setValues(dValues) (that's why I said to keep the range in a separate variable). So as an example, the following will clear columns B through F if column A has a 0
function test(){
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i = 1; i <sheets.length; i++) {
sheets[i].getRange("C2").setValue(new Date());
var dRange = sheets[i].getDataRange();
var dValues = dRange.getValues();
for (var j = 1; j < dRange.getLastRow(); j++){
if (dValues[j][0] == 0) {
for (var c = 1; c < 6; c++) {
dValues[j][c] = ""
}
}
}
dRange.setValues(dValues);
}
}
For a single sheet of ~170 rows this takes a few seconds. One thing to note is that I wrote it based on your script, you set a date value in C2 however in your sript (and thus in the one I wrote based on yours) that falls within the range you are checking to be cleared, so double check your ranges

Cypress cy.type({enter} fails when used multiple times within for loop

The cypress cy.type({enter} fails when I use this in a for loop to enter multiple data in text field. If I have to enter only one value then in that case that works.
Please suggest me some solution for this. Here is my code :-
value = cat, bat, mice, fox
enterMultipleValue(value) {
var val = value;
var val_str = val.split(",");
for (var i = 0; i < val_str.length; i++) {
cy.get('input[mat-option="text"]')
.type(val_str[i]+"{enter}", { force: true });
// .wait(3000)
// .type('{enter}');
}
}
The code works ok, but what do you want to see?
const value = "cat, bat, mice, fox"
const vals = value.split(",");
for (var i = 0; i < val_str.length; i++) {
cy.get('input[mat-option="text"]')
.type(val_str[i]+"{enter}")
.wait(3000)
.type('{enter}');
}
This shows "cat bat mice fox" in the input box.
If you want to see them one at a time, add a .clear() command
const value = "cat, bat, mice, fox"
const vals = value.split(",");
for (var i = 0; i < val_str.length; i++) {
cy.get('input[mat-option="text"]')
.type(val_str[i]+"{enter}")
.wait(3000)
.clear();
}
This shows each one for 3 seconds, then the next, etc.
But is this a select box? mat-option is used on an Angular Material Select. Are you trying to do a multiple-select?

Google script, ignoring for loop - Spreadsheet

I've been searching for scripts and stuff to look up but, seems like google api has been changed too much or I'm dumb and doesn't know how to execute old scripts and make them work.
I keep getting these errors Parsing error... Yahoew this helps to a lot. Not knowing what line. So I made my own.
function amountOfColors(color, range){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var orgColor = ss.getRange(color).getBackground();
var range = ss.getRange(range);
var x = 0;
Logger.log("I was here before the loop.");
for (var i; i < range.getNumRows(); i++) {
Logger.log("Entered Row loop");
for (var j; j < range.getNumColumns(); j++) {
Logger.log("Entered Columns loop");
var curCell = range.getCell(i, j);
Logger.log("curCell is : " & curCell);
if(curCell.getBackground() == orgColor) {
Logger.log("curCell color is : " & curCell.getBackground());
x++;
}
}
}
Logger.log("END");
return x;
};
As you can see I pretty much made it log for every thing. However this is what it returns in the logfile:
[14-02-20 04:00:53:445 CET] I was here before the loop.
[14-02-20 04:00:53:445 CET] END
Not even touching my loop?
All I want this script to is to take a color from a original position and then find how many cells has that color and return it. Really simple script.
Hope someone can enlighten me on this one. I've tried to install scripts from the script gallery that does similar but they return errors too.
Here's a picture of a setup:
http://b.imgdrp.com/PCoT.PNG - I realise it says B33:B35, but even with A it doesn't work.
Adding my own answer in case someone would have similar problem.
function amountOfColors(color, range){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]
var orgColor = sheet.getRange(color).getBackground();
var range = sheet.getRange(range);
var x = 0;
for (var i = 1; i <= range.getNumRows(); i++) {
for (var j = 1; j <= range.getNumColumns(); j++) {
var curCellColor = range.getCell(i,j).getBackground();
if(curCellColor == orgColor)
x++;
}
}
return x;
};
Other than this I changed the way I called my function:
instead of:
=amountOfColors("A35", "A33:A35")
you need to use:
=amountOfColors("A35"; "A33:A35")
As you can see semi-colon instead of comma.
My apologies for posting and fixing it so fast, seems like all I needed was that 1 extra hour to get crafty. At least hope someone might gain something from this.
If there is any questions about the code feel free to add a comment, I'll try to explain.
Best Regards Qvintus.

Replace certain cell values in a column

Disclaimer: I am Newb. I understand scripting a little, but writing it is a pain for me, mostly with loops and arrays, hence the following.
I am attempting to pull all of the data from a specific column (in this case H [8]), check each cell's value in that column and if it is a y, change it to Yes; if it's n, change it to No; if it's empty, leave it alone and move onto the next cell.
Here's what I have so far. As usual, I believe I'm pretty close, but I can't set the value of the active cell and I can't see where I'm messing it up. At one point I actually changed ever value to Yes in the column (so thankful for undo in these cases).
Example of Sheet:
..... COL-H
r1... [service] <-- header
r2... y
r3... y
r4... n
r5... _ <-- empty
r6... y
Intent: Change all y's to Yes and all n's to No (skip blank cells).
What I've tried so far:
Function attempt 1
function Thing1() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "y") {
data[i][0] == "Yes";
}
}
}
Function attempt 2
function Thing2() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data.setValue("No");
} else if (data[i][0] == "y") {
data.setValue("Yes");
}
}
}
Usage:
Once I'm done here, I want to modify the function so that I can target any column and change one value to another (I already have a method for that, but I need to be able to set the value). It would be like so: =replace(sheet, col, orig_value, new_value). I will post it as well below.
Thanks in advance for the help.
Completed Code for searching and replacing within a column
function replace(sheet, col, origV1, newV1, origV2, newV2) {
// What is the name of the sheet and numeric value of the column you want to search?
var sheet = Browser.inputBox('Enter the target sheet name:');
var col = Browser.inputBox('Enter the numeric value of the column you\'re searching thru');
// Add old and new targets to change (Instance 1):
var origV1 = Browser.inputBox('[Instance 1:] What old value do you want to replace?');
var newV1 = Browser.inputBox('[Instance 1:] What new value is replacing the old?');
// Optional - Add old and new targets to change (Instance 2):
var origV2 = Browser.inputBox('[Instance 2:] What old value do you want to replace?');
var newV2 = Browser.inputBox('[Instance 2:] What new value is replacing the old?');
// Code to search and replace data within the column
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
var lrow = ss.getLastRow();
var rng = ss.getRange(2, col, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == origV1) {
data[i][0] = newV1;
} else if (data[i][0] == origV2) {
data[i][0] = newV2;
}
}
rng.setValues(data);
}
Hope this helps someone out there. Thanks Again #ScampMichael!
The array named data was created from the values in the range and is independent of the spreadsheet after it is created so changing an element in the array does not affect the spreadsheet. You must modify the array and then put the whole array back where it came from.
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data[i][0] = "No";
} else if (data[i][0] == "y") {
data[i][0] = "Yes";
}
}
rng.setValues(data); // replace old data with new
}

Resources