Running numbers like INV-2026-0001
Apps Script recipes › Dates, text and numbers
A counter in Script Properties, raised under a lock so two people never get the same number; starts again each year.
File Code.gs
/** "INV-2026-0001", "INV-2026-0002", … */
function nextNumber_(prefix) {
const lock = LockService.getScriptLock();
lock.waitLock(10000);
try {
const year = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy');
const key = `counter_${prefix}_${year}`;
const props = PropertiesService.getScriptProperties();
const n = Number(props.getProperty(key) || 0) + 1;
props.setProperty(key, String(n));
return `${prefix}-${year}-${String(n).padStart(4, '0')}`;
} finally {
lock.releaseLock();
}
}
Good to know
- Script Properties keep the counter even when rows are deleted, so numbers are never reused.
Let the AI put it in your appGAS AI Builder knows every recipe here. Describe your app and it uses this code where it fits, in a Google Apps Script project in your own Drive.
Use it in a project