Snippet Beginner Sheets
Get or create a sheet by name
A reusable helper that returns a tab by name and creates it if missing — so your Northwind scripts never crash on a renamed sheet.
Published Jan 15, 2026
Half of Northwind’s “the script broke” reports come down to one thing: a tab was renamed or deleted, and getSheetByName returned null. Reach for this helper instead — it returns the tab if it exists, and creates it on the spot if it doesn’t.
The helper
/**
* Return a sheet by name, creating it if it does not exist.
* @param {string} name The tab name, e.g. 'Invoices'.
* @param {Spreadsheet} [ss] Defaults to the active spreadsheet.
* @return {Sheet} The existing or newly created sheet.
*/
function getOrCreateSheet(name, ss) {
ss = ss || SpreadsheetApp.getActiveSpreadsheet();
return ss.getSheetByName(name) || ss.insertSheet(name);
}
Using it
Drop it into any Northwind workbook script and stop null-checking by hand:
function logInvoiceRun() {
// Always returns a usable sheet — no null, no crash.
const log = getOrCreateSheet('Invoice Log');
log.appendRow([new Date(), 'invoices generated']);
}
If you also want fresh headers when the tab is brand new, check the row count:
function getLogSheet() {
const sheet = getOrCreateSheet('Invoice Log');
if (sheet.getLastRow() === 0) {
sheet.appendRow(['timestamp', 'event']); // seed headers once
}
return sheet;
}