提交谷歌表格(脚本)时写一个唯一的代码

时间:2014-02-27 20:14:40

标签: google-apps-script

发送表单时,“sendform(e)”会向插件旁边的单元格添加一个唯一的代码,但我无法理解为什么不为我工作。

任何人都可以帮助我吗?

    function sendform(e) 
{ 



var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];

e.namedValues['CODICE'] = CodeGen("llnnnnn");

}

function CodeGen(CodeStr,ExclStr) {
........
}

2 个答案:

答案 0 :(得分:0)

你真的没有为我提供足够的代码来查看你的代码发生了什么,但这是我从头开始编写的一个解决方案,你可以修改以满足你的需求。我评论了它的废话,所以你可以看到它是如何工作的。我还从许多来源中找到了一个随意的字母数字发生器,我觉得很舒服可以满足你的需求。

function formResponses(e) {
  var formData = e.values;//obtains form data submitted
  var ss = SpreadsheetApp.openById('1eVEM9vN7Hzn-pKhtyDHBXhQvoVmePJr6Su5ipTK9Shs');//opens response Spreadsheet that is linked to form, put your response sheet ID here
  var sh = ss.getSheetByName('Responses');//opens response sheet to read/write, put your response sheet name here
  var userEmail = formData[2];//gets user email, but does not store it, it is discarded after email is sent.
  var lastCol = 4;//sets column where uniqueId will be written
  var lastRow = sh.getLastRow();//row where new form entries are added
  var speciesResponse = formData[1];//retrieves user's response to the form question

  //the next line retrieves a list of existing IDs from the last column of the resopnse sheet
  var uuIdArray = [sh.getRange(2,lastCol,sh.getLastRow(),1)];
  //the next line create a new random string for this submission by calling the generation string
  //with arguments a string of 8 16-bit characters
  var randomId = genRandomString(8,16);
  //the following for() loop compares the newly generated random string
  //to the existing UniqueIds, and if there is a duplicate,
  //it regenerates another randomId and resets i = 0 to compare from the first unique ID again.
  //if there is not a duplicate within the list, it will finish the for loop and move on.
  for (var i = 0; i < uuIdArray.length; i++){
    if (randomId == uuIdArray[i]){
      var randomId = genRandomString(8,16)
      i = 0
    }
  }
  sh.getRange(lastRow,lastCol,1,1).setValue(randomId);
  Logger.log(randomId);
  var species = speciesId(speciesResponse);
  Logger.log(species);
  var fromAlias = selectSenderEmailAlias();
  sendSpeciesEmail(userEmail,species, randomId, fromAlias);
  Logger.clear();//clears the log of identifying information, specifically user's email address.
  sh.getRange(2,3,sh.getLastRow(),1).clear();
}

//SUPPLEMENTAL FUNCTIONS CALLED FROM THE FORM POST:

//This is the important part for generating the random 8 digit Unique ID  
function genRandomString(len, bits){
  bits = bits || 36;
  var outStr = "", newStr;
  while (outStr.length < len)
  {
    newStr = Math.random().toString(bits).slice(2);
    outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  }
  return outStr.toUpperCase();
}
//The rest of this is for fun to test the form and a mailer to notify the user of their species status
function speciesId(speciesResponse){
  var species = speciesResponse;
  switch (species){
    case "Yes":
      var userType = "Human";
      break;
    case "No":
      var userType = "Other";
      break;
  }
  return userType;
}

//selects an Alias to obscure mailing address from form author
function selectSenderEmailAlias(){
  var alias = GmailApp.getAliases();
  Logger.log(alias[0]);
  return alias;
}

//constructs and mails the user their results.
function sendSpeciesEmail(userEmail,species,randomId,fromAlias){
  var userEmail = userEmail;
  var emailFrom = 'Helperbot@hyperbole.com';
  var species = species;
  Logger.log(species);
  var fromAlias = fromAlias;
  var subject = 'Species evlauation quiz. Confirmation# '+randomId;
  var randomId = randomId;
  switch(species){
    case "Human":
      var body = 'Congrats! You are a human!';
      break;
    case "Other":    
      var body = 'Uh oh. I have bad news. You may be a cat (or another sub-human species).  Please contact your physician for further evaluation';
      break;
  }
  MailApp.sendEmail(userEmail, subject, body, {from: fromAlias});
}

以下是查看文件的文件夹:https://drive.google.com/folderview?id=0B_5rNbCI5MM9ellxaGdrWlItNVE&usp=sharing该脚本位于响应电子表格中的工具&gt;管理脚本下。

这是测试它是否有效的形式(https://docs.google.com/forms/d/1Cz6U92w-vAyoofshbXcScNi6S2WWdRLw0srYfguplnU/viewform)。查看电子表格中C列中的响应,以查看生成的唯一ID。我不可能验证ID迭代器永远不会搞砸,但是通过代码的设计,我无法想象它不会起作用。但是,作为测试用例,没有办法将值放在那里,因为它会在提交表单后立即生成randomId。

我试图再次为随机字符串生成器找到我的源代码,但我不能,因为我关闭了一堆标签。我向原作者道歉。

答案 1 :(得分:0)

使用此功能生成随机字符串非常完整。

function CodeGen(CodeStr,ExclStr) {
// a = code string, b = string of characters to exclude
  var i=0;
  var alen = CodeStr.length;
  var areturn = ""
  for (i=0;i<=alen;i++)
       {
       areturn=areturn+RandChar(CodeStr.substring(i,i+1),ExclStr);
       }
  return(areturn);
}

function RandChar(a,b) {
  var usestring = GenString(a,b);
  var randchar = Math.floor(Math.random()*usestring.length);
  return(usestring.substring(randchar,randchar+1));    
       }

function GenString(a,b) {
  var numstring = ExcludeString('0123456789',b);
  var charstring = ExcludeString('ABCDEFGHIJKLMNOPQRSTUVWXYZ',b);
  var allstring = numstring+charstring;
  switch (a) {
    case 'a': 
      result = allstring; 
      break;
    case 'n': 
      result = numstring; 
      break;
    case 'l': 
      result = charstring; 
      break;
    case 'v': //118 = v
    case 'w': //119 = w
    case 'x':
    case 'y':
      result = allstring.substr(0, a.charCodeAt(0)-122+allstring.length);
      break;
    default: result = a;
             }
  return(result);
}

function ExcludeString(FullText, ExcludeText) {
  FullText=FullText+''
  ExcludeText=ExcludeText+''
  var areturn = ''
  var SearchText = ''
  for (i=0;i<=FullText.length;i++)
    {
    SearchText = FullText.substring(i,i+1)
    if (ExcludeText.search(SearchText) == -1)
      {  
      areturn=areturn+SearchText;
      }
    }
    return(areturn);
}

示例:

CodeGen(“xa-aaaa-aaaa”)给出PN-4ZES-UN57或0T-TY1R-7NUI

CodeGen(“aa-aaaa-aaaa”,“0O1I5S”)给出PN-4ZEU-UNT7或3T-TY4R-7NUK

CodeGen(“llnnnnn”)给出了VF98029,两个字母,然后是五个数字

CodeGen(“IC-nnnn”)给出IC-7233或IC-2743,始终以IC开头

CodeGen(“nn-nnnn”)给出01-2945或65-2329

CodeGen(“nnnnnn”,“0135679”)给出884422或2428242,不包括

我觉得这个功能非常有用,因为它非常有用。我想感谢这个功能的原作者,但我不知道谁创建了一个非常好的工具(代码)。

相关问题