清除不同表上的匹配单元格(无序列)

时间:2019-11-17 14:30:14

标签: javascript google-apps-script google-sheets

所以...我在比较不同表内容时遇到问题。

我基本上需要清除单元格数据相同的内容,但是表是无序的,并且当我运行代码时,只清除第一行。

所以我对此进行了修改(因为它只清除了表格的第一行):

function clearSourceValues(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceTable = ss.getSheetByName("Encaminhamento");  
  var targetTable = ss.getSheetByName("testeBD");


  var rowCount = targetTable.getLastRow() + 1;


  var sourceValues = sourceTable.getRange(2, 8, rowCount, 1).getValues();
  var targetValues = targetTable.getRange(2, 3, rowCount, 1).getValues();



  for (var i = 0; i < targetValues.length; i++){ // Modified
    var clearRange = targetTable.getRange(i + 2, 2, 1, 8); // Modified
    if (targetValues[i][0] == sourceValues[i][0]){
      clearRange.clear();
    };
  };;
};

对此:

  for (var i = 0; i < targetValues.length; i++){ 
    var clearRange = targetTable.getRange(i + 2, 2, 1, 8); 
    for (var j = 0; j < sourceValues.length; j++){ 
      if (targetValues[i][0] == sourceValues[j][0]){
        clearRange.clear();
      };
    };
  };

但是现在当我运行它时,每个单元格都被清除了。

2 个答案:

答案 0 :(得分:2)

在源3列和目标8列中的匹配项上清除源范围和目标范围

function clearSourceandDestinationValues(){
  var ss=SpreadsheetApp.getActive();
  var ssh=ss.getSheetByName("Encaminhamento");  
  var tsh=ss.getSheetByName("testeBD");
  var srg=ssh.getRange(2,8,ssh.getLastRow()-1,1);
  var trg=tsh.getRange(2,3,tsh.getLastRow()-1,1);
  var svA=srg.getValues();
  var sA=svA.map(function(r){return r[0]});//flatten
  var tvA=trg.getValues();
  var tA=tvA.map(function(r){return r[0]});//flatten
  svA.forEach(function(r,i){if(tA.indexOf(r[0])!=-1) {ssh.getRange(i+2,1,1,ssh.getLastColumn()).clear();}});//clears source range
  tvA.forEach(function(r,i){if(sA.indexOf(r[0])!=-1) {tsh.getRange(i+2,1,1,tsh.getLastColumn()).clear();}});//clears destination range  
}

答案 1 :(得分:0)

地图功能很好用

function clearSourceValues() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sourceTable = ss.getSheetByName("Encaminhamento");
    var targetTable = ss.getSheetByName("testeBD");
    var sourceValues = sourceTable.getRange(2, 8, (targetTable + 1), 1).getValues();
    var targetValues = targetTable.getRange(2, 3, (targetTable + 1), 1).getValues();
    var mapSourceTable = sourceValues.map(function(r) {
        return r[5]
    }) //this return you the whole data in the column "f"
    var mapTargetTable = targetValues.map(function(r) {
        retunrn r[0]
    }); //this return you the whole data in the column "a"
    for (var i = 1; /*remove the header*/ i < mapSourceTable.length; i++) {
        var eltToCompare = mapSourceTable[i];
        mapSourceTable.forEach(function(elt, index) {
            //remove the header
            if (index > 0) {
                if (eltToCompare == elt) {
                    targetTable.deleteRow(index + 2);
                }
            }

        });
    }