如果 Table 1 中存在但 Table 2 中不存在,则复制值

Copy value if it exists in Table 1 but not in Table 2

基本上我有两个表。 Table 1 有一个特定事件的所有出席者的列表。 Table 2 列出了参加上述活动的组织的所有成员。我正在尝试复制所有参加该活动的非成员的列表。所以我脑子里的逻辑是试图遍历 Table 2 并查看 Table 1 中是否也存在该值。如果不存在,我将尝试将其复制到列表中。

    var attendants = currentS.getRange("M2:M").getValues(); //this is the list of all members that attended an event
       for (var x = 2; x <= checkLast; x++) {
          newcheck = currentS.getRange(x,5).getValue(); //this is getting the name of the attendants
       if (attendants.indexOf(newcheck) == -1) {
             var columnM = currentS.getRange("M1:M").getValues(); //trying to see if name of attendants is in the list of all members that attended the event. 
             var columnMlast = columnM.filter(String).length;
             var final = currentS.getRange(columnMlast+1,13);
    
             final.setValue(currentS.getRange(x,5).getValue()); //if it attendant is not in the list of members that attended, copies the name into a new list. 

每当我 运行 代码时,我最终只会得到整个服务员列表,而不会过滤掉任何内容。我希望我已经清楚了,并提前致谢!!

解释:

您可以在 members 的列表中使用 filter method to find the items of attendants that are not included,这将导致 new_members 的列表附加在 members 的底部。

使用此解决方案,您不需要 for 循环,最重要的是,您不需要在计算量大的循环中使用 setValuegetValue

解决方案:

我无法使用你的代码,因为你提供的代码片段中没有定义变量。

我将向您展示一个示例(sheet 和代码),您可以使用它们来调整当前的解决方案。

示例脚本:

function myFunction() {
  const ss = SpreadsheetApp.getActive();
  const currentS = ss.getSheetByName("Sheet1");
  const members = currentS.getRange("M2:M").getValues().flat().filter(r=>r!='');
  const attendants = currentS.getRange("N2:N").getValues().flat().filter(r=>r!='');
  const new_members = attendants.filter(a=>!members.includes(a)).map(nm=>[nm]);
  console.log(new_members) // output: [ [ 'guest1' ], [ 'guest2' ], [ 'guest3' ], [ 'guest4' ] ]
  currentS.getRange(members.length+2,13,new_members.length,1).setValues(new_members);
}

示例sheet(输入-输出):