删除行,并根据列中的唯一值将其添加到另一个工作表

时间:2020-06-23 18:53:44

标签: google-apps-script google-sheets

有人可以帮忙吗? 我已经查看了本网站上的其他问题,但没有找到满意的答案。

我有一个工作表接收来自表单的响应-如果新表单提交的F列(第6列)的值与F列中的现有条目的值相同,我想将旧条目行移至存档表(从此工作表中删除它们)。这将使响应表在F列中仅保留唯一的条目。

这样做的原因是我只想查看当前条目,但将较早的条目保存在档案中。

如果有人可以帮助您,那就太好了。

谢谢。

1 个答案:

答案 0 :(得分:0)

如果我们想拥有:

  1. 所有回复的表格(存档) 和
  2. 仅包含每种最新响应的表(由F列确定)

我建议保持响应表不变,将响应表用作“归档”,然后将新表指定为仅新响应的“实时”列表。更改表单响应表很麻烦,应该仅将其保存为存档,而不进行编辑。

这是一种使用响应表作为“存档”并指定新表作为最新响应的“实时”视图的解决方案。

首先,您必须创建一个表单提交触发器: 在“脚本编辑器”页面上,单击编辑>当前项目的触发器 将触发器和更改事件类型添加到:在表单提交时, 并确保在顶部选择了正确的功能(在本例中为myFunction)

使用此脚本:

function myFunction(e) {
  //  //Use this commented section to refer to a live sheet in another Spreadsheet
  //  let url = "[Enter url for Spreadsheet here]"
  //  let liveSheet = SpreadsheetApp.openByUrl(url).getSheets()[0];
  let liveSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];
  let responseSheet = SpreadsheetApp.getActiveSheet();  
  let newRow = responseSheet.getActiveRange().getRow();
  let liveLastRow = liveSheet.getLastRow();
  let responseLastColumn = responseSheet.getLastColumn();
  let matchColumn = 6;
  //Get list of entries in match column to find duplicates, 
  //Initialization and IF statement are in case there are 0 rows.
  let oldEntries = [];
  console.log(liveLastRow, liveLastRow > 0);
  if (liveLastRow > 0) {
  oldEntries = liveSheet.getRange(1, matchColumn, liveLastRow, 1).getValues();
  }
  //Load in data from new response entry
  let newEntry = responseSheet.getRange(newRow, 1, 1,  responseLastColumn).getValues()[0];
  console.log("Existing rows in live sheet: ", oldEntries.length, "\nNew Entry: ", newEntry);
  console.log("Scanning old entries for duplicate...");
  //Loop through all old entries to search for match
  for (entry = 0; entry < oldEntries.length; entry++) {
    console.log("Is this a match in entry row #", (entry+1), "? \n", String(newEntry[matchColumn-1]), String(oldEntries[entry][0]));
    //If matches existing row
    if (String(newEntry[matchColumn-1]) === String(oldEntries[entry])) {
      console.log("Found a match!", "Copying new entry to row: ", (entry + 1), "with ", newEntry.length, "columns");
      //Copy to Live sheet
      liveSheet.getRange((entry + 1), 1, 1, newEntry.length).setValues([newEntry]);
      console.log("Replaced old entry ", oldEntries[entry][0], " with new entry:", newEntry);
      console.log("done :)");
      return
    }
    console.log("No Match...");
  }
  //If no existing entry, then just append the new entry to bottom of list.
  console.log("Appending new entry to bottom of live sheet...");
  liveSheet.appendRow(newEntry);
  console.log("done :)");
}

我做了一张测试表格并运行了。作品。 逻辑如下: 此条目是否已存在于实时工作表上? 如果是,请用此新条目替换该条目, 如果否,请在列表底部添加新条目。