Need a tab that might not exist yet? This helper returns the sheet if it's there, or inserts it and returns the new one — no null checks scattered through your bootstrap.
What you'll need
- A
Spreadsheetobject (getActiveSpreadsheet(),openById(), etc.) - The exact tab name you want
How to use this snippet
function getOrCreateSheet(ss, name) {
var sheet = ss.getSheetByName(name);
if (!sheet) {
sheet = ss.insertSheet(name);
}
return sheet;
}
function ensureImportTab() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = getOrCreateSheet(ss, 'Import');
if (sheet.getLastRow() === 0) {
sheet.appendRow(['timestamp', 'status', 'notes']);
}
return sheet;
}
Tips:
- Tab names are case-sensitive —
'Import'and'import'are different sheets. - If you care about position, pass an index as the second arg to
insertSheet(name, index).
Happy Coding!
