Search code examples
google-apps-scriptgoogle-sheets-apigoogle-apps-script-editor

Google Sheet Script Incrementing Not working the way its expected but its concatinating


Google Sheet Script should increment the value of the column 1 by 1, but it is concatenating 1. I am not great at google Scripts. Could you help me find what am i Doing wrong.

function onFormSubmit(e) {
  var columnNumber = 1; // first col is 0
  var initialId = 18;   
  var sp = PropertiesService.getScriptProperties();
  var id = sp.getProperty("req_id") || initialId ;
  id = id.split(".")[0] ;
  e.range.offset(0, columnNumber, 1, 1).setValue(id);
  sp.setProperty("req_id", id + 1);
}

The output is looking like this in the sheet

1811
18111
181111
18111111

Solution

    • You want to put the value to the cell and you want to add 1 every run.
    • You want to use PropertiesService for this situation.

    If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

    Modification points:

    • I think that the reason of your issue is that the values retrieved by getProperty() is the string type. In this case, even when the number is put with setProperty(), when the value is retrieved with getProperty(), the retrieved value is the string type.
    • When the number is used for split(), an error occurs. Because split() is used for the string.

    Modified script:

    When your script is modified, it becomes as follows.

    function onFormSubmit(e) {
      var columnNumber = 1; // first col is 0
      var initialId = 18;
      var sp = PropertiesService.getScriptProperties();
      var id = Number(sp.getProperty("req_id")) || initialId; // Modified
      e.range.offset(0, columnNumber, 1, 1).setValue(id);
      sp.setProperty("req_id", id + 1);
    }
    

    References:

    If I misunderstood your question and this was not the result you want, I apologize.