Google Apps Script Writing to Spreadsheet Column One Step Behind - javascript

Weird problem here. I'm writing a script using Google Apps Scripts. Part of the script takes values from 1 Range/array ("a"), finds the value in a second Range/array ("b"), and then writes the corresponding value from a 3rd Range/array ("c") into column F in the spreadsheet. It's basically a vlookup.
When I check the code, debugger, etc. everything looks fine. And the output into the sheet looks good too. Except when I ran the program, the last value was missing from the sheet. When I ran the program slowly using the debugger, it seems that for some reason the values aren't being printed to column F until the following round of the loop is complete. This doesn't really make any sense based on the values of the variables at the time. So for example, when i=4, it should be printing to F6. But instead it prints the previous value to F5. All of the correct values are in the correct place in the end (except the last one), but the timing seems to be off on when that happens which is why I'm missing my last value.
Note: I have tried seeing if it's just about a time delay, and that doesn't seem to be the case. I've reloaded the spreadsheet, waited a while, etc. It's just 1 step behind.
Code is below, pretty simple I think. Any help would be appreciated
loop1:
for(i=0;i<a.length;i++){
loop2:
for(j=0;j<b.length;j++){
if(a[i].valueOf() == b[j].valueOf()){
sheet.getRange("F"+(i+2)).setValue(c[j]);
break loop2;
}
}
}

I tried to re-create your situation with the following code:
function myFunction() {
var a = ['one','6','match'];
var b = ['two','Vee','match'];
var c = ['three','Vee','match'];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getActiveSheet();
loop1:
for(i=0;i<a.length;i++){
loop2:
for(j=0;j<b.length;j++){
//Logger.log('a[i].valueOf() ' + a[i])
//Logger.log('b[j].valueOf() ' + b[j])
Logger.log(a[i].valueOf() == b[j].valueOf());
if (a[i].valueOf() == b[j].valueOf()) {
Logger.log('they match!');
Logger.log('i: ' + i);
Logger.log('j: ' + j);
sh.getRange("F"+(i+2)).setValue(c[j]);
break loop2;
}
}
}
};
The code runs, and it puts a value into cell F4 with the array data provided.
The Log:
false
false
false
false
false
false
false
false
true
they match!
i: 2
j: 2

Related

JSLint confusion in Javascript alerts are not declared

Hey so I'm using JSLint under the assumption I'm using a browser and tolerating multiple vars and whitespace mess.
The whole program works, but I have a few problems, according to JSLint. First off, I'm trying to use alert(string) to make pop-up error messages, but JSLint is telling me the alerts are undeclared, I haven't found a resource on the internet that's explained how to make this not happen yet.
Secondly, I have loops that look like this:
function setMixedList() {
"use strict";
clearResults();
var n = "0";
var l = "0";
var text = "";
while (n < numList.length && l < letList.length) {
document.getElementById("listInput").value =
text += numList[n] + letList[l];
n ++;
l ++;
}
This loop in particular takes two separate arrays and mixes them together in order; one containing numbers (1-7) and the other containing letters (a-g) in a way so they appear in a text box like this:
1 a 2 b 3 c 4 d 5 e 6 f 7 g
JSLint doesn't like two things about this. The first is that in the
document.getElementById("listInput").value =
text += numList[n] + letList[l];
section of the loop, JSLint tells me the "+=" is unexpected. When I edit that to:
text = text + numList[n] + letList[l];
JSLint tells me the "=" is unexpected and I'm not sure how to take these things out without making my program unable to work.
The other important part of this is the
n ++;
l ++;
section of code. I know JSLint doesn't like ++, but if I make the code
n+= 1;
l+= 1;
The string doesn't come out right, with some characters undefined because I'm not just dealing with numbers. Anybody know how to fix these problems?
To answer the first part
JSLint is telling me the alert
This can be resolved by following one of the way . In jslint options set
"devel:true" which will enables things like Alert, console,prompt.Check this link to know more about it.
Secondly set browser option set to true in your .jshintrc and use window.alert instead of alert

For loop keeps breaking out after 1 instance - Apps Script

I have looked everywhere I can think of for anything that can provide an answer to this. First time posting a question here - I can usually find my answers. I have a for loop that is pulling information from a range of data that is formatted in one cell like this: 09/01/2016 - Status changed to active.
The loop is supposed to first see how many values are in that column then go one by one and split the data into a simple array, post it into two columns on a separate sheet, then move onto the next one. The problem is that it stops after the first entry.
var numEntries = dataSheet.getRange(1,i+1,1000).getValues();
var lastEntry = numEntries.filter(String).length;
if (lastEntry == 7) {
// no change data to date
sheet.getRange(18,3).setValue("No changes yet");
} else {
var changeData = dataSheet.getRange(8,i+1,lastEntry-7).getValues();
for (var y = 0; y < changeData.length; y++) {
var changeHistory = changeData[y][y].split(" - ");
sheet.getRange(nextRow+1,2).setValue(changeHistory[0]);
sheet.getRange(nextRow+1,3).setValue(changeHistory[1]);
nextRow++;
Logger.log(nextRow);
Logger.log(changeData.length);
Logger.log(y);
}
}
I know that it is executing properly because it is properly setting the "No changes yet" value when there are no entries. Variable nextRow starts at a value of 17, and the log properly shows changeData.length with the number of entries and y being equal to 0. But then it stops. It doesn't follow the loop that y is still less than changeData.length. Any help is very much appreciated!
[edit] - I also want to point out that it does properly split and populate the first value into the two cells I want it to, so the whole for statement does work, it just doesn't loop. [edit]
[16-09-29 15:37:48:514 CDT] 18.0 [16-09-29 15:37:48:515 CDT]
11.0 [16-09-29 15:37:48:515 CDT] 0.0
changeData is an n*1 Array.
You are increasing y and and you are also trying to get the y-th column from changeData.
After the first iteration this is undefined because there's only one column.
undefined does not have a split method throwing an exception and terminating the script. (You may not see this exception, these kinds of exceptions aren't always shown to the user for some reason)
Try
var changeHistory = changeData[y][0].split(" - ");
instead.

How to tell if two cells are equal in Google Apps Script for Google Spreadsheet

I am writing a script to bind two cells to always hold the same value after every edit. My script so far looks like this:
function myEdit(event){
var ss = event.source.getActiveSheet();
var r = event.source.getActiveRange();
var bind1 = ss.getRange("D11:D11").getCell(1,1);
var bind2 = ss.getRange("D10:D10").getCell(1,1);
var editedCell = r.getCell(1,1);
Logger.log("checking");
if (editedCell === bind1){
Logger.log("Condition was Met!");
bind1.copyTo(bind2);
}
else if (editedCell === bind2){
Logger.log("Condition was met!");
bind2.copyTo(bind1);
}
else{
Logger.log("No condition was met.");
}
When I change the value in either of the bound cells, nothing is copied anywhere else. When I check the execution logs, it appears everything went fine
[14-07-21 10:47:06:215 EDT] Execution succeeded [0.884 seconds total runtime]
But when I check the Logger logs, I get
[14-07-21 10:55:49:260 EDT] checking
[14-07-21 10:55:49:260 EDT] No condition was met.
For some reason, the program is not recognizing that editedCell and bind1 are the same object, when I edit cell D11.
By checking the values of bind1 and editedCell, the values are the same so they must be referring to the same cell, but the equality operator is not working to check whether they are the same range.
For some reason, the program is not recognizing that editedCell and bind1 are the same object, when I edit cell D11.
The reason that the identity operator === doesn't work in this case is that what is being compared is the Range, not the content of the cells in those ranges. Like Sandy suggests, you need to get the values first, and compare those.
However, comparison isn't needed, is it? Your stated objective is to ensure D10 and D11 contain the same value after every edit. Since the only edit that can affect either is a change to themselves, you can ignore any edit made to any cells but D10 or D11. Further, if either of them changes, and myEdit() is invoked, you know they are different, so you can just copy the newly changed value to the other cell.
Something like this:
function myEdit(event){
// To check whether we need to do anything, find which cell was edited.
// Get the A1 notation for the changed cell.
var cellA1 = event.range.getA1Notation();
if (cellA1 == "D10") {
// D10 changed, so copy value to D11
event.range.offset(1,0).setValue(event.value);
}
else if (CellA1 == "D11") {
// D11 changed, so copy value to D10
event.range.offset(-1,0).setValue(event.value);
}
// Any other cell, do nothing.
}

javascript for loop not behaving as expected

I know this is really basic but I am new to Javascript
This is a piece of code from a battleship game I am working on for a class
function displayMyBoats(ship){
for (var i = 0; i<ship.length; i++)
{
alert("ship.length = " + ship.length);
alert("Ship[i]= " + ship[i]);
document.getElementById( "Set_" + ship[i] ).src = fnImageShip;
alert("i = " + i);
}
}
I am testing with a ship array that is 5 elements. Everything works fine until it reaches 5, then all of a sudden it thinks the length of the array is 8.
There is no code to increase the length of ship array, so what would cause it to add to the length of the array?
The alerts are my testing to see what all the values are at.
To give you a hint, try adding an alert whenever your script is either entering or exiting the displayMyBoats(). Suddenly jumping to 8 indicates that it's entering the method a second time, this time with a ship of len 8.
Confirm or deny this theory by adding this alert after your for loop block:
alert('exiting displayMyBoats()');`
Perhaps you see more if you use console.log(ship); instead of alert(); - if you are using Firebug/Console.

For Loop repeats first loop twice

I have this for loop, and it seems to be repeating the first loop twice (x=0) and then not doing the last one (x=2)
for (x=0;x<=2;x++)
{
if (document.getElementById("sub"+catCount+x).value != "")
{
if (nonums.test(document.getElementById("sub"+catCount+x).value))
{
total = total + parseFloat(document.getElementById("sub"+catCount+x).value);
}
}
alert(x);
}
In other words, I get two alert boxes with "0" in them, then one with "1" in it, and that's it.
Can anyone tell me what I'm not seeing here? Why doesn't it just progress through the loop normally (0,1,2)?
that is literally the only spot I use
the variable x on any page.
It works for me.
for (x=0;x<=2;x++)
{
alert(x);
}
You can test it at console.
I don't think you want the variable x to be global in scope. Try it with the "var" keyword:
for (var x=0;x<=2;x++)
...
I can paste this in my address bar and it will produce 0, 1, 2.
javascript:for (var x=0;x<=2;x++) {alert(x);}
I tried it in IE, FF and Chrome.

Categories

Resources