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

Time:11-16

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());

CodePudding user response:

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:

CodePudding user response:

Tryu this:

function myfunk() {
  var ss = SpreadsheetApp.getActive();
  var sh = ss.getSheetByName("RawData");
  Logger.log(parseInt(sh.getRange(sh.getLastRow(), 1).getValue().split(' ')[1])   1);
}
  • Related