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

Google Sheets Script Keep Leading 0's in a sku after incrementing by 1

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

}

>Solution :

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

Description

You can use the Utilities.formatString() to pad the left with zeros.

Edit script

skuFinal = skuBegin + Utilities.formatString("%05d",skuNum);
sh.getRange("A2").setValue(skuFinal);

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