Get or Create a Sheet by Name

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 Spreadsheet object (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!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free themes and snippets — plus optional Co-Pilot when you want a boost (1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension