表单提交时自动递增

时间:2014-02-25 00:43:58

标签: google-apps-script

我正在尝试为每个表单提交添加一个带有两位数年份前缀的自动递增唯一ID。我复制了Serge Insas的答案in this post中的代码,并且正在尝试实施所请求的两位数年份here

function OnForm(){
    var sh = SpreadsheetApp.getActiveSheet()
    var startcell = sh.getRange('A2').getValue();
      if(! startcell){sh.getRange('A2').setValue('PQOT-14-0001');return}; // this is only to       handle initial situation when A1 is empty.
    var colValues = sh.getRange('A2:A').getValues();// get all the values in column A in an array
    var year = Utilities.formatDate(new Date, "PST", "yy")
    var max=0;// define the max variable to a minimal value
        for(var r in colValues){ // iterate the array
        var vv=colValues[r][0].toString().replace(/[^0-9]/g,'');// remove the letters from the string to convert to number
          if(Number(vv)>max){max=vv};// get the highest numeric value in th column, no matter what happens in the column... this runs at array level so it is very fast
      }
    max++ ; // increment to be 1 above max value
    sh.getRange(sh.getLastRow(), 1).setValue(Utilities.formatString('PQOT-'+year+'-%04d',max));// and write it back to sheet's last row.
}

以上代码返回“PQOT-14-000X”。我需要编辑它以删除无关的文本和年份,以便它将正确增加。有什么建议?

1 个答案:

答案 0 :(得分:0)

您可以使用substr() string method使用否定参数获取最后4位数:代码如下:

var vv=colValues[r][0].toString().substr(-4).replace(/\D/g,'')

请注意,我使用了替换regex的另一个变体来获取任何非小数的数值D