I have the code below. It's supposed to increment ID upon entering "Yes" in col B. It does the work to a certain extent, but it always keep the number of zeros the same while it's supposed to decrease by 1 when ID reach 10s and by 2 when it reaches 100s etc.
function onEdit(e){
var AUTOINC_COLUMN = 0;
var HEADER_ROW_COUNT = 1;
var zeros = "000000";
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var worksheet = spreadsheet.getSheetByName("Sheet6");
var rows = worksheet.getDataRange().getNumRows()-1;
var vals = worksheet.getSheetValues(1, 1, rows+1, 2);
var r = worksheet.getActiveCell();
if (r.getColumn() == 2 && worksheet.getName()=='Sheet6' && r.getValue() == "Yes") {
for (var rowx = HEADER_ROW_COUNT; rowx < vals.length; rowx++) {
try {
var id = vals[rowx][AUTOINC_COLUMN];
Logger.log(id);Logger.log((""+id).length ===0);
if ((""+id).length === 0) {
worksheet.getRange(rowx+1, AUTOINC_COLUMN+1).setValue("STU" + ("0".repeat(zeros.length - rowx.toString.length)) + rowx);
}
} catch(ex) {
}
}
}
}
It seems the toString function is not returning the right value for some reason. Can someone please help?
While checking your code, I've seen that you are not using toString
as method, causing it to return the number length which is always 1.
Just change it to toString()
and it should work.
I've tested it on my side and it did do what you expect.
Sample output:
For additional reference, please see the usage