首页 > 解决方案 > 如何使用谷歌脚本检查两个谷歌工作表,并将重复项移动到新工作表?

问题描述

我正在尝试做一些看似简单的事情。我有一张巨大的 20k 联系人表,其中有些联系人的电子邮件很糟糕。我已经编制了我想要提取的不良电子邮件列表,并且想要编写一个脚本,从“20k”列表中的“不良”列表中找到电子邮件,将每封不良电子邮件的整行复制到“新"(生成)表,然后从 20k 列表中删除该行。

一切正常,直到它需要检查重复项、复制它们并删除旧的(嵌套的 for 循环)。现在它会多次复制所有内容(是否重复),然后删除整个工作表。这是问题代码:

 // Find duplicates from the two sheets and move them to the "FindDupes" sheet
  var dupes = false;
  var dataMDS = sourceSheetMDS.getDataRange().getValues();
  var dataETR = sourceSheetETR.getDataRange().getValues();
  for (i = numETRRows; i >= 0; i--) {
    for (j = numMDSRows; j >= 0; j--) {
      if  (sourceSheetETR[i,1] == sourceSheetMDS[j,1]) {
        dupes = true;

        // Copy the desired rows to the FindDupes sheet
        for (var k = 1; k <= numMDSCols; k++) {
          var sourceRange = sourceSheetMDS.getRange(1,k,j);
          var nextCol = newSheet.getLastColumn() + 1;
          sourceRange.copyTo(newSheet.getRange(1,nextCol,j));
        }
        sourceSheetMDS.deleteRow(j);
      }
    }
  }

这是整个项目:

function findDuplicates() {

  // List the columns you want to check by number (A = 1)
  var CHECK_COLUMNS = [1];

  //Declare the Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();  

  // Get the active sheet and info about it
  // Main Database Sheet
  var sourceSheetMDS = ss.getSheetByName("test");
  var numMDSRows = sourceSheetMDS.getLastRow();
  var numMDSCols = sourceSheetMDS.getLastColumn();

  // Get the active sheet and info about it
  // Emails To Rremove Sheet
  var sourceSheetETR = ss.getSheetByName("Emails to Remove");
  var numETRRows = sourceSheetETR.getLastRow();
  var numETRCols = sourceSheetETR.getLastColumn();

  // Create the sheet of duplicates
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var newSheet = ss.insertSheet("FindDupes");

  // Find duplicates from the two sheets and move them to the "FindDupes" sheet
  var dupes = false;
  var dataMDS = sourceSheetMDS.getDataRange().getValues();
  var dataETR = sourceSheetETR.getDataRange().getValues();
  for (i = numETRRows; i >= 0; i--) {
    for (j = numMDSRows; j >= 0; j--) {
      if  (sourceSheetETR[i,1] == sourceSheetMDS[j,1]) {
        dupes = true;

        // Copy the desired rows to the FindDupes sheet
        for (var k = 1; k <= numMDSCols; k++) {
          var sourceRange = sourceSheetMDS.getRange(1,k,j);
          var nextCol = newSheet.getLastColumn() + 1;
          sourceRange.copyTo(newSheet.getRange(1,nextCol,j));
        }
        sourceSheetMDS.deleteRow(j);
      }
    }
  }


  // Alert the user with the results
  if (dupes) {
    Browser.msgBox("Possible duplicate(s) found, moved, and deleted.");
  } else {
    Browser.msgBox("No duplicates found.");
  }
};

谢谢!

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


改变

if  (sourceSheetETR[i,1] == sourceSheetMDS[j,1]) {
        dupes = true;
...

if  (dataETR[i,1] == dataMDS[j,1]) {
        dupes = true;
...

解释:

您必须比较值而不是(不存在)工作表数组条目。


推荐阅读