I am trying to increment a SKU by one using a button on Google Sheets and I am unable to keep leading 0's after incrementing the SKU by 1. The code below will increment the SKU by 1 and keep formatting except for leading 0's. The SKU format is: CBP-2022-00001. Any help with this would be much appreciated. I am new to the language, so let me know if you need more information.
function incrementSku() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('cheat_sheet');
var sku = sh.getRange("B15").getValue();
var skuEnd = sku.slice(-5);
var skuBegin = sku.slice(0,9);
var skuNum = Number(skuEnd) 1;
var skuFinal;
skuEnd = skuNum.toString();
skuFinal = skuBegin skuEnd;
sh.getRange("B15").setNumberFormat('@STRING@').setValue(skuFinal);
}
CodePudding user response:
Description
You can use the Utilities.formatString() to pad the left with zeros.
Edit script
skuFinal = skuBegin Utilities.formatString("d",skuNum);
sh.getRange("A2").setValue(skuFinal);
Reference