Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Script splits text and adds 1 to value doesnt record the correct number

For the life of me I dont know what is wrong with this code it records the correct number but doesn’t add the number correctly unless i type it in myself.

https://docs.google.com/spreadsheets/d/1kxIzE_HcPWd82LpGqCXNxg0yczhcnA6yOYRnB4GuAZo/edit?usp=sharing

var column = 0;
  var HEADER_ROW_COUNT = 1;

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var worksheet   = spreadsheet.getSheetByName("RawData");
  var rows        = worksheet.getDataRange().getNumRows();
  var vals        = worksheet.getSheetValues(1, 1, rows, 1);

  var max = 0;

  for (var row = HEADER_ROW_COUNT; row < vals.length; row++) {  
     var splitstring = vals[row][0].toString().split(" ");
 
  
    var splitstring = vals[row][0].toString().split(" ");
    var id = splitstring[1];
    
   Logger.log(id)
    if (max < id) {
      Logger.log(id)
        max = id+1;
         Logger.log(max)
    }
  }
  var LastRow = worksheet.getLastRow();
 
  
 
  worksheet.getRange(LastRow+1,1).setValue("PO# " + max.toString());

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Although I’m not sure whether I could correctly understand your goal, in your script, var id = splitstring[1]; retrieved by var splitstring = vals[row][0].toString().split(" "); is the string type. I thought that this might be the reason of your issue. When this is reflected to your script, it becomes as follows.

From:

var id = splitstring[1];

Logger.log(id)
if (max < id) {

To:

var id = Number(splitstring[1]);
Logger.log(id)
if (max <= id) {

Note:

  • In your script, for example, you might be also able to use var max = Math.max(...vals.map(([v]) => Number(v.split(" ").pop()))) + 1; instead of your for loop.

Reference:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading