I had posted a question months ago regarding deleting a row if a value in it exists in another sheet.
This is the accepted answer in my previous post.
function deleteRowInSheet1() {
var s1 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet1');
var s2 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet2');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var resultArray = [];
for(var n in values1){
var keep = true
for(var p in values2){
if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
keep=false ; break ;
}
}
if(keep){ resultArray.push(values1[n])};
}
s1.clear()
s1.getRange(1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
Now, my question is what if there are more than 1 sheet to be compared to. Let's say I have 4 sheets.
Sheet1:
NAME | PLACE | AGE
Carl | Florida | 45
Mike | Florida | 41
Suzy | Florida
Sheet 2:
NAME | PLACE | AGE
Mike | Florida | 41
Sheet 3:
NAME | PLACE | AGE
Mike | Florida | 41
Sheet 4:
NAME | PLACE | AGE
Mike | Florida | 41
The script should delete Mike Florida row in Sheet 2 to 4 since it has duplicate data in Sheet 1. Column 1 and 2, again are the basis to compare all the data in the 4 sheets since the values will be unique. I tried to modify the answered script but I can't seem to make it run. I understood the logic but not sure which part I missed:
This is my code:
function deleteRowInSheets1to3() {
var s1 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet1'); //this is the basis of all sheets. values to be compared is column 2
var s2 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet2');
var s3 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet3');
var s4 = SpreadsheetApp.openById("SS_ID").getSheetByName('Sheet4');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var values3 = s3.getDataRange().getValues();
var values4 = s4.getDataRange().getValues();
var resultArray = [];
for(var n in values1){
var keep = true
for(var p in values2){
if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
keep=false ; break ;
}
for(var q in values3){
if( values1[n][0] == values3[q][0] && values1[n][1] == values3[q][1]){
keep=false ; break ;
}
for(var r in values4){
if( values1[n][0] == values4[r][0] && values1[n][1] == values4[r][1]){
keep=false ; break ;
}
}
}
}
if(keep){ resultArray.push(values1[n])};
}
s1.clear()
s1.getRange(1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
Thanks a bunch for any advice! :)