Google Scripts delete duplicates from select range (not whole sheet)

对着背影说爱祢 提交于 2020-12-26 11:04:41

问题


Below is a Google Sheets script for deleting duplicate rows from a spreadsheet. While it does work in removing duplicate rows it also destroys in-cell formulas in the process. I currently have a series of sheets where all of the raw data is contained within Columns A:P and all of my formulas are relegated to Columns Q:T.

In my attempts to limit the following script to work only on Columns A:P I receive a missing argument error upon running the script.

var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange("A2:P").getValues();

TL:DR, I love the script, but I want to limit the range upon which it is ran. Any help? Thank you.

https://developers.google.com/apps-script/articles/removing_duplicates

function removeDuplicates() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var newData = new Array();
for(i in data){
var row = data[i];
var duplicate = false;
for(j in newData){
  if(row.join() == newData[j].join()){
    duplicate = true;
  }
}
if(!duplicate){
  newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, 
newData[0].length).setValues(newData);
}

EDIT: I believe the following is above a valid question, but I would like to add a new observation that may have some impact on what's happening(??). When I initiate a find and replace from within sheets to remove all instances of the word 'null' then sheets removes null and leaves every other cell alone. However if I run a script to remove 'null' it reformats all of my cells changing dates & times to decimals. etc. Is there a means by which to run a script and avoid overall unintended actions such as sheet wide reformatting?


回答1:


You will need to use getRange() function to specify the range on which you want to work with.

var sheet = SpreadsheetApp.getActiveSheet();
var rng = sheet.getRange("A2:P")
var data = rng.getValues();

Also, you clear the entire sheet with this line sheet.clearContents(); instead use this

rng.clearContents()

That way you only clear contents in the range specified by rng
Your final code should look like this

function removeDuplicates() {
var sheet = SpreadsheetApp.getActiveSheet();
var rng = sheet.getRange("A2:P")
var data = rng.getValues();
var newData = new Array();
for(i in data){
var row = data[i];
var duplicate = false;
for(j in newData){
  if(row.join() == newData[j].join()){
    duplicate = true;
  }
}
if(!duplicate){
  newData.push(row);
}
}
rng.clearContents();
sheet.getRange(1, 1, newData.length, 
newData[0].length).setValues(newData);
}


来源:https://stackoverflow.com/questions/48655614/google-scripts-delete-duplicates-from-select-range-not-whole-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!