i need a help to register only unique values inside the google spreadsheet behind the web script app
currently to save I use this script, practical find a way to block the launch if you already have values the same values in the spreadsheet.
basically there are two fields "cod" and "val"
if "cod" and "val" have already been registered before, it would need to show a message that these data are repeated.
I tried to do a check, but you can only do it in one "cod" field,
I would like to do it in both "cod" and "val" fields
https://docs.google.com/spreadsheets/d/1ZfIqw6_pkt1AdWsayyk1LdW_I6lU2yjsY1VfxfJneCA/edit#gid=0
function save_on_sheet(Data){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ZfIqw6_pkt1AdWsayyk1LdW_I6lU2yjsY1VfxfJneCA/edit#gid=0");
var ws = ss.getSheetByName("page");
const cod = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues().map(r => r[0].toString().toLowerCase());
const posicaoIndex = cod.indexOf(Data.cod.toString().toLowerCase());
if (posicaoIndex === -1) {
ws.appendRow([
Data.cod,
Data.val
])
return 'NEW';
} else {
return 'DUPLICATE';
}
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<label for="cod">COD:</label>
<input type="text" id="cod"><br><br>
<label for="val">VALUE:</label>
<input type="text" id="val"><br><br>
<input type="submit" value="SAVE UNIQUE SHEET" onclick="save()">
</body>
<script>
function save(){
Data = {}
Data.cod = document.getElementById("cod").value;
Data.val = document.getElementById("val").value;
google.script.run.withSuccessHandler(retorno).save_on_sheet(Data);
}
function retorno(mensagem_retorno){
alert(mensagem_retorno);
}
</script>
</html>
function save_on_sheet(Data){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ZfIqw6_pkt1AdWsayyk1LdW_I6lU2yjsY1VfxfJneCA/edit#gid=0");
var ws = ss.getSheetByName("page");
const dataVal = ws.getRange(2,1,ws.getLastRow()-1, 2).getDisplayValues();
Logger.log(dataVal);
for(var i=0; i<dataVal.length;i++){
var rowData = dataVal[i];
if(rowData[0]==Data.cod.toString().toLowerCase() && rowData[1]==Data.val.toString().toLowerCase()){
//Exit function, duplicate found
return 'DUPLICATE';
}
}
//No duplicate found. Append new data
ws.appendRow([
Data.cod,
Data.val
]);
return 'NEW';
}
cod
and values
data in the spreadsheet using Range.getDisplayValues() which will return a 2-d array of string values.cod
and values
to Data.cod
and Data.values
. If match found, return "DUPLICATE"
, if no match found, append the Data
and return "NEW"