首页 > 解决方案 > 如何在提交表单时自动将表单响应的最后一行复制到另一张表的最后一行

问题描述

我正在尝试为以下问题找到解决方案:每次有人回答我的表单时,都会在名为“formresponses”的谷歌表中创建一个新行。然后我在同一个文件中得到了另一张表,我将这些新行复制到其中。目前,我正在使用下面的代码,该代码在单击分配了此功能的按钮后运行该功能。

但我知道我知道有一个叫做 Trigger 的东西在提交新表单后会自动触发该函数。不幸的是,我是编码新手,并不真正知道如何使用它。我尝试搜索互联网,但我没有找到在我的情况下如何使用它。

所以基本上可以正常工作的实际复制功能是

function copy(){
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
 
  var formsheet = ss.getSheetByName("formresponses");
  var targetsheet = ss.getSheetByName("targetsheet");
  
  var numOfCol = formsheet.getLastColumn(); // Last Column Indexnumber
  
  var lastrowForm = formsheet.getLastRow();
  var lastrowTarget = targetsheet.getLastRow(); 
  var targetrow = lastrowTarget + 1;       // Lastrow() always gives the last row that contains content, so to get the next empty row we simply add +1 
  
  var rangetoCopy = formsheet.getRange(lastrowForm,1,1,numOfCol).getValues();

  targetsheet.getRange(targetrow,1,1,numOfCol).setValues(rangetoCopy);  
  
}

每次提交新的表单答案时,我怎样才能自动完成这项工作?我真的很感谢你们的帮助!:)

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


In case multiple submits come at the same time, you may not get the expected row correctly with getLastRow

You need an on form submit trigger

The event passed to such trigger include all the answers, so just append it to the target sheet

function formSubmit(e) {
  const id = 'ID of Spreadsheet';
  const ss = SpreadsheetApp.openById(id);
  const targetsheet = getSheetByName('targetsheet');
  targetsheet.appendRow(e.values);
}

References:


推荐阅读