1

I'm using Google forms to create a spreadsheet that I want sorted automatically by datestamp Z-A. The sorting will be triggered whenever anyone fills out a form.

I think the way to do it is:

  1. ask if there is a "copy of Form responses" on spreadsheet...
    • if yes, clear all contents...
    • else...
  2. copy spreadsheet to "copy of form responses"...
  3. sort according to timestamp

Below is what I've cobbled so far. It works only the first time a response is recorded. I'm not a coder so any help is appreciated. If someone could also point me to a list of commands with basic syntax I'd be grateful.

function CopySheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var msheet = ss.getSheetByName("Form Responses"); 
    msheet.copyTo(ss);

    var CopySheet = ss.getSheetByName("Copy of Form Responses"); 
    CopySheet.sort(1,   false); // here 1 is for column no. 1 that 
               // is "Column A" and true is for ascending, make it 
               // false if you want descending.
};
4

1 回答 1

1

您可以在没有脚本的情况下通过QUERY()在副本表中使用来完成此操作。例如,如果您将此函数放在副本表的单元格 A1 中,并将密钥替换为您的表单响应电子表格,您最终将得到一个反向时间戳排序的响应副本:

=Query(ImportRange(spreadsheet_key,"Form Responses!A:Z"), "select * order by Col1 desc")

此数据将定期刷新(约 5 分钟),因此它将反映新的表单提交,但不是实时的。

注意:当ImportRange()用作 的源数据时Query,您需要使用ColN符号来引用查询字符串中的列。

或者,您可以在接收表单提交的电子表格中生成表单提交触发函数,并将排序的表单响应复制到您的副本表。下面的函数就是这样做的。您需要将其设置为电子表格表单提交事件的触发功能。有关如何测试此类功能的信息,请参阅如何在 GAS 中测试触发功能?.

function copyFormSubmissions(e) {
  var sourceSheet = e.range.getSheet();
  var data = sourceSheet.getDataRange().getValues();
  var headers = data.splice(0,1)[0]; // remove headers from data
  data.sort(reverseTimestampOrder);  // Sort 2d array
  data.splice(0,0,headers);          // replace headers

  var destId = "--copy-sheet-ID--";
  var destSheet = SpreadsheetApp.openById(destId).getSheetByName('Sheet1');
  destSheet.clear();
  destSheet.getRange(1,1,data.length,data[0].length).setValues(data);
};

function reverseTimestampOrder(a,b) {
  // Timestamp is in first (zero-th) column
  return (b[0]-a[0]);
}

如果有人还可以向我指出具有基本语法的命令列表,我将不胜感激。

Google Apps Script API 类和方法参考在这里。如果您正在学习,请尝试教程(同一个地方),我建议您通过某种形式的电子学习来熟悉 Javascript - CodeAcademy.com 是一个很好的起点,因为它介绍了所有的语言结构,而不是专注于网页开发,使其与 Googls Apps Script 非常相关。

于 2013-12-10T04:01:03.620 回答