I am currently working a small Google Apps Script that will get Data from a from and proceed to paste some of this data in a table where it finds matching ID / invoice number.
However, when these two for statement are following each other, the script takes ages to executed because it proceeds to add the data in the specified columns, great but also, from the first empty row up until the very end of the sheets it copies that same data indefinitely.
for (var i = 0; i < caData.length; i++) {
if (caData[i][3] == ID) {
if (tax == "VAT") {
feuilleCA.getRange(i + 1, 14).setValue(amount);
feuilleCA.getRange(i + 1, 15).setValue(mode);
feuilleCA.getRange(i + 1, 16).setValue(now);
} else {
feuilleCA.getRange(i + 1, 12).setValue(amount);
feuilleCA.getRange(i + 1, 13).setValue(mode);
feuilleCA.getRange(i + 1, 16).setValue(now);
}
}
}
for (var i = 0; i < caData.length; i++) {
if (caData[i][1] == invoice) {
if (tax == "VAT") {
feuilleCA.getRange(i + 1, 14).setValue(amount);
feuilleCA.getRange(i + 1, 15).setValue(mode);
feuilleCA.getRange(i + 1, 16).setValue(now);
} else {
feuilleCA.getRange(i + 1, 12).setValue(amount);
feuilleCA.getRange(i + 1, 13).setValue(mode);
feuilleCA.getRange(i + 1, 16).setValue(now);
}
}
}
To ensure that I did not make any mistake in the code previously provided, I proceeded to make tests with
The first for statement (ID) and it worked perfectly, no issue
The second for statement (invoice) and it worked perfectly, no issue.
However when combined, it seems to create some sort of infinite loop.
As you will tell I am not an expert, but I am already very happy with what I could accomplish, so please bare with me. From what I understand there is no counter indication as to using two for statements followed by each other. What would your suggestions be?
2
Answers
Instead of relying on the loop end condition that is
i < caData.length
you can have a break condition within the loop body. Something like:if(feuilleCA.getRange(i + 1, X).getValue() == "") break;
where
X
is any cell which has data for each row. I remember facing this issue working with Microsoft Excel sheets in C#. Might work on google sheets as well.You don’t show your entire script so I had to make some assumption. First, that the the
caData
is the same size as the data you want to replace infeuilleCA
. Second, thatnow
is the current date. And lastly that only values are infeuilleCA
columns L:Q.First I get caData. Then I only get the data from
feuilleCA
columns L:Q. I replace the data infData
and put it back.I’ve eliminated the need for 2 for loops. And I’ve eleminated the need for all the
setValue()
call by merging it into 1setValues()
call.Reference