I modified the code given by @Alan Wells in Find position of a cell containing a specific string but I don't know why it still inserts the matched string into the next empty cell. It supposed to only insert IF no match found in the entire data range declared in values array. Please help to modify my code below. Thanks.
function findValueInRange () {
var ss=SpreadsheetApp.openById('THE_SHEET_ID').getSheetByName('staff'),
theLastColumn = ss.getLastColumn(),
theLastRow = ss.getLastRow(),
lastrow=theLastRow,
name='Dahlia';
var values = ss.getRange(1,1,theLastRow,theLastColumn).getValues();
var i=0,rownum=0,thisRow,colvalue,whatToFind = name,j=0;
for(i=0;i<values.length;i++) {
thisRow = values[i];
for (j=1;j<thisRow.length;j++) {
colvalue = thisRow[j];
switch(colvalue){
case whatToFind :Logger.log("The string is in row: "+(i+1)+" and column: "+(j+1));break;
case '' : Logger.log("just blank");break;
default : // when no found match
var lrow=NextCellRng(theLastColumn);//a custom fn to get the last non-blank row number of the last column only
ss.getRange(lrow,theLastColumn-1).setValue(name); //insert name in the next cell range
ss.getRange(lrow,theLastColumn).setValue('attended'); // insert status next to the name
break;
}
}
}
}
Here is the spreadsheet that I need to refer to lookup for the string:-
This spreadsheet stores 2 columns of data which are the name and status 'attended'. I want to utilise the spreadsheet spaces to it's max limit of rows and columns, so once it reaches the max row of first column, it supposed to continue in the next column and so forth. So, the data and search range would grow with the new inserted data when not found. It should be able to grow until the max row and max col that a sheet could handle. In this question, we assume that the max row (5 rows) is reached and that's why the next column is filled and so forth.
Whenever a name is entered in a googleform, my custom function should be able to do a validation first:-
- getValue from the response sheet (in this question, 'Dahlia' is for sampling test)
- search for the name in the lookup sheet. If exist, return the col & row number & out of loop. But if not, insert the name in the next blank cell and out of loop
But what i noticed is, regardless the name exist or not, the name is still will be inserted. And worse, I realized is the insert process is an infinite loop for that same last column. I had to terminate it at the Project trigger dashboard when I advertently clicked "dismiss" on the script earlier.
When name 'Dahlia' is not found the updated sheet should look like below:-