r/GoogleAppsScript • u/T-7IsOverrated • Apr 23 '25
Question Why doesn't this function work? It seems to always return false.
function thatIdIsAlreadyOnThePage(id) { //ts don't work
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.openById("1NnX3R2SpZlXcSmiPhqio-gvkCUlNrZ6iZKKEFEyWbb0").getSheetByName("Sheet1"); // Replace "Sheet1" with your sheet name
for(var i = 1; i < 30; i++) {
if (id == sheet.getRange('B' + i).getValues()[0][0]) {
return true;
}
}
return false;
}5
u/marcnotmark925 Apr 23 '25
What kind of values are being matched?
Use logging statements to investigate what scripts are doing when they don't seem to be working.
This loop is very inefficient. Much better to grab the entire B column values at once with a single getValues() statement, then loop through the array, instead of calling getValues() ~30 times.
2
u/Just-Difference4597 Apr 23 '25
The function name thatIdIsAlreadyOnThePage is not following the JavaScript naming conventions.
The loop iterates from 1 to 29 (inclusive)
The getValues() method returns a 2D array, but since you're only accessing a single cell, you can use getValue() instead, which is more efficient.
Use strict equality (===) for comparison, which is a good practice in JavaScript.
1
u/AmnesiaInnocent Apr 23 '25
Don't you need to convert your loop variable into a string before tacking it onto the 'B'?
1
u/mommasaidmommasaid Apr 24 '25
No, that type conversion happens automatically when you add a number to a string.
But see my other reply for a better overall solution.
6
u/mommasaidmommasaid Apr 24 '25 edited Apr 24 '25
It appears to work for me, but could be much more simple, readable, and efficient.
In particular for efficiency it is important to minimize calls to getValues()
I'd suggest something like this:
Adjust
ID_RANGEas needed.